text
stringlengths
4
1.08k
Python: unescape special characters without splitting data,""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])"
How can I disable logging while running unit tests in Python Django?,logging.disable(logging.CRITICAL)
Adding url to mysql row in python,"cursor.execute('INSERT INTO index(url) VALUES(%s)', (url,))"
Convert column of date objects in Pandas DataFrame to strings,df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
python regex get first part of an email address,s.split('@')[0]
Python Pandas: drop rows of a timeserie based on time range,df.query('index < @start_remove or index > @end_remove')
Python Pandas: drop rows of a timeserie based on time range,df.loc[(df.index < start_remove) | (df.index > end_remove)]
How to count the Nan values in the column in Panda Data frame,df.isnull().sum()
Turn Pandas Multi-Index into column,df.reset_index(inplace=True)
python getting a list of value from list of dict,[x['value'] for x in list_of_dicts]
python getting a list of value from list of dict,[d['value'] for d in l]
python getting a list of value from list of dict,[d['value'] for d in l if 'value' in d]
Converting NumPy array into Python List structure?,"np.array([[1, 2, 3], [4, 5, 6]]).tolist()"
Converting string to tuple and adding to tuple,"ast.literal_eval('(1,2,3,4)')"
How to keep a list of lists sorted as it is created,dataList.sort(key=lambda x: x[1])
Python: Uniqueness for list of lists,"list(map(list, set(map(lambda i: tuple(i), testdata))))"
Python: Uniqueness for list of lists,[list(i) for i in set(tuple(i) for i in testdata)]
"In Django, how do I check if a user is in a certain group?",return user.groups.filter(name='Member').exists()
"In Django, how do I check if a user is in a certain group?","return user.groups.filter(name__in=['group1', 'group2']).exists()"
Dynamically changing log level in python without restarting the application,logging.getLogger().setLevel(logging.DEBUG)
How to transform a tuple to a string of values without comma and parentheses,""""""""""""".join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))"
What is the simplest way to swap char in a string with Python?,""""""""""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])"
Drawing a huge graph with networkX and matplotlib,"plt.savefig('graph.png', dpi=1000)"
delete items from list of list: pythonic way,my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
Find an element in a list of tuples,[item for item in a if 1 in item]
Find an element in a list of tuples,[item for item in a if item[0] == 1]
How can I get the index value of a list comprehension?,"{p.id: {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}"
how to uniqify a list of dict in python,[dict(y) for y in set(tuple(x.items()) for x in d)]
How do I load a file into the python console?,"exec(compile(open('file.py').read(), 'file.py', 'exec'))"
Get the number of rows in table using SQLAlchemy,rows = session.query(Congress).count()
Execute Shell Script from python with variable,"subprocess.call(['test.sh', str(domid)])"
How to read a .xlsx file using the pandas Library in iPython?,"dfs = pd.read_excel(file_name, sheetname=None)"
Reading hex to double-precision float python,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))"
Indexing numpy array with another numpy array,a[tuple(b)]
How to find all possible sequences of elements in a list?,"map(list, permutations([2, 3, 4]))"
Sort a list in python based on another sorted list,"sorted(unsorted_list, key=presorted_list.index)"
How to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1)
Creating a zero-filled pandas data frame,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)"
string find,x.find('World')
string find,x.find('Aloha')
string find,'sdfasdf'.index('cc')
string find,'sdfasdf'.index('df')
string find,str.find('a')
string find,str.find('g')
string find,"str.find('s', 11)"
string find,"str.find('s', 15)"
string find,"str.find('s', 16)"
string find,"str.find('s', 11, 14)"
Sort list of date strings,"sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))"
Regular expression in Python sentence extractor,"re.split('\\.\\s', text)"
Regular expression in Python sentence extractor,"re.split('\\.\\s', re.sub('\\.\\s*$', '', text))"
Python - How to cut a string in Python?,"""""""foobar""""""[:4]"
Python - How to cut a string in Python?,s.rfind('&')
Python - How to cut a string in Python?,s[:s.rfind('&')]
Using a variable in xpath in Python Selenium,"driver.find_element_by_xpath(""//option[@value='"" + state + ""']"").click()"
append to a file,"with open('test.txt', 'a') as myfile:
myfile.write('appended text')"
append to a file,"with open('foo', 'a') as f:
f.write('cool beans...')"
append to a file,"with open('test1', 'ab') as f:
pass"
append to a file,"open('test', 'a+b').write('koko')"
How can I split a string into tokens?,"print([i for i in re.split('([\\d.]+|\\W+)', 'x+13.5*10x-4e1') if i])"
Python: Check if a string contains chinese character?,"re.findall('[\u4e00-\u9fff]+', ipath)"
String splitting in Python,s.split('s')
How to start a background process in Python?,"subprocess.Popen(['rm', '-r', 'some.file'])"
Elegant way to transform a list of dict into a dict of dicts,"dict((d['name'], d) for d in listofdict)"
print date in a regular format,datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
print date in a regular format,time.strftime('%Y-%m-%d %H:%M')
Finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)"
How do I get a list of indices of non zero elements in a list?,"[i for i, e in enumerate(a) if e != 0]"
How to get integer values from a string in Python?,"map(int, re.findall('\\d+', string1))"
How can I know python's path under windows?,os.path.dirname(sys.executable)
Moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_label_position('top')
Moving x-axis to the top of a plot in matplotlib,ax.xaxis.tick_top()
Moving x-axis to the top of a plot in matplotlib,ax.xaxis.set_ticks_position('top')
Parsing non-zero padded timestamps in Python,"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')"
Open images,"img = Image.open('picture.jpg')
img.show()"
Open images,"img = Image.open('picture.jpg')
Img.show"
How do I abort the execution of a Python script?,sys.exit(0)
How do I abort the execution of a Python script?,sys.exit('aa! errors!')
How do I abort the execution of a Python script?,sys.exit()
Find maximum with limited length in a list,"[max(abs(x) for x in arr[i:i + 4]) for i in range(0, len(arr), 4)]"
How to set the current working directory in Python?,os.chdir('c:\\Users\\uname\\desktop\\python')
How to set the current working directory in Python?,os.chdir(path)
How to remove all integer values from a list in python,"no_integers = [x for x in mylist if not isinstance(x, int)]"
How do I match contents of an element in XPath (lxml)?,"tree.xpath("".//a[text()='Example']"")[0].tag"
convert dictionaries into string python,""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])"
Detecting non-ascii characters in unicode string,"print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))"
Detecting non-ascii characters in unicode string,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))"
Convert a String representation of a Dictionary to a dictionary?,"ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")"
Easiest way to remove unicode representations from a string in python 3?,print(t.decode('unicode_escape'))
String encoding and decoding from possibly latin1 and utf8,print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8'))
merge lists into a list of tuples,"zip(list_a, list_b)"
merge lists into a list of tuples,"list(zip(a, b))"
python pandas dataframe to dictionary,df.set_index('id').to_dict()
python pandas dataframe to dictionary,df.set_index('id')['value'].to_dict()
Can I sort text by its numeric value in Python?,"sorted(list(mydict.items()), key=lambda a: map(int, a[0].split('.')))"