text
stringlengths 4
1.08k
|
|---|
Remove punctuation from Unicode formatted strings,"return re.sub('\\p{P}+', '', text)"
|
How can I convert a unicode string into string literals in Python 2.7?,print(s.encode('unicode_escape'))
|
How do I check if an insert was successful with MySQLdb in Python?,cursor.close()
|
Selenium Webdriver - NoSuchElementExceptions,driver.implicitly_wait(60)
|
Python sort list of lists over multiple levels and with a custom order,"my_list.sort(key=lambda x: (order.index(x[0]), x[2], x[3]))"
|
Python counting elements of a list within a list,all(x.count(1) == 3 for x in L)
|
List of non-zero elements in a list in Python,"[1, 1, 0, 0, 1, 0]"
|
find last occurence of multiple characters in a string in Python,max(test_string.rfind(i) for i in '([{')
|
How to pass dictionary items as function arguments in python?,my_function(**data)
|
Django - taking values from POST request,"request.POST.get('title', '')"
|
How do I turn a dataframe into a series of lists?,df.T.apply(tuple).apply(list)
|
for loop in Python,"list(range(0, 30, 5))"
|
How to specify where a Tkinter window opens?,root.mainloop()
|
How to import a module from a folder next to the current folder?,"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))"
|
Split data to 'classes' with pandas or numpy,[x.index.tolist() for x in dfs]
|
How to convert datetime to string in python in django,{{(item.date | date): 'Y M d'}}
|
Delete column from pandas DataFrame,"df = df.drop('column_name', 1)"
|
How to get a list which is a value of a dictionary by a value from the list?,"reverse_d = {value: key for key, values in list(d.items()) for value in values}"
|
Cross-platform addressing of the config file,config_file = os.path.expanduser('~/foo.ini')
|
"how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))"
|
Change the colour of a matplotlib histogram bin bar given a value,plt.show()
|
How to delete a file without an extension?,os.remove(filename)
|
Python - split sentence after words but with maximum of n characters in result,"re.findall('.{,16}\\b', text)"
|
Python 10 colors in plot,plt.show()
|
How do you pass arguments from one function to another?,"some_other_function(*args, **kwargs)"
|
Pandas: Sorting columns by their mean value,"df.reindex_axis(df.mean().sort_values().index, axis=1)"
|
Format timedelta using string variable,"'timedelta(%s=%d)' % ('days', 2)"
|
Format() in Python Regex,"""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')"
|
change current working directory in python,os.chdir('chapter3')
|
python/numpy: how to get 2D array column length?,a.shape[1]
|
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.get(0)
|
Is there a way to use two if conditions in list comprehensions in python,"[i for i in my_list if not i.startswith(('91', '18'))]"
|
Reading data blocks from a file in Python,f = open('file_name_here')
|
Sorting Python list based on the length of the string,"print(sorted(xs, key=len))"
|
Watch for a variable change in python,pdb.set_trace()
|
Pandas: Mean of columns with the same names,"df.groupby(by=df.columns, axis=1).mean()"
|
Python pandas - grouping by and summarizing on a field,"df.pivot(index='order', columns='sample')"
|
How do I set color to Rectangle in Matplotlib?,plt.show()
|
How to apply numpy.linalg.norm to each row of a matrix?,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)"
|
Pandas: transforming the DataFrameGroupBy object to desired format,"df.columns = ['code/colour', 'id:amount']"
|
Stdout encoding in python,print('\xc5\xc4\xd6'.encode('UTF8'))
|
How do you divide each element in a list by an int?,myList[:] = [(x / myInt) for x in myList]
|
Regex for location matching - Python,"re.findall('(?:\\w+(?:\\s+\\w+)*,\\s)+(?:\\w+(?:\\s\\w+)*)', x)"
|
Generate a heatmap in MatPlotLib using a scatter data set,plt.show()
|
Get column name where value is something in pandas dataframe,"df_result = pd.DataFrame(ts, columns=['value'])"
|
Remove empty strings from a list of strings,str_list = list([_f for _f in str_list if _f])
|
Deleting a line from a file in Python,"open('names.txt', 'w').write(''.join(lines))"
|
Pandas: transforming the DataFrameGroupBy object to desired format,df = df.reset_index()
|
How to transform a time series pandas dataframe using the index attributes?,"pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')"
|
Make a python list constant and uneditable,return my_list[:]
|
Plotting dates on the x-axis with Python's matplotlib,plt.gcf().autofmt_xdate()
|
Python get focused entry name,"print(('focus object class:', window2.focus_get().__class__))"
|
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]
|
Determine whether a key is present in a dictionary,"d.setdefault(x, []).append(foo)"
|
pretty print pandas dataframe,"pd.DataFrame({'A': [1, 2], 'B': ['a,', 'b']})"
|
pandas data frame indexing using loc,"pd.Series([pd.Timestamp('2014-01-03'), 'FRI', 'FIZZ'])"
|
getting every possible combination in a list,"['cat_dog', 'cat_fish', 'dog_fish']"
|
How to grab numbers in the middle of a string? (Python),"[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]"
|
Reverse the order of legend,"ax.legend(handles[::-1], labels[::-1], title='Line', loc='upper left')"
|
Python: import symbolic link of a folder,sys.path.append('/path/to/your/package/root')
|
How to check the existence of a row in SQLite with Python?,"cursor.execute('insert into components values(?,?)', (1, 'foo'))"
|
How do I clone a Django model instance object and save it to the database?,obj.save()
|
How to get only div with id ending with a certain value in Beautiful Soup?,soup.select('div[id$=_answer]')
|
Get contents of entire page using Selenium,driver.page_source
|
Return the column name(s) for a specific value in a pandas dataframe,"df.ix[:, (df.loc[0] == 38.15)].columns"
|
Reversing bits of Python integer,"int('{:08b}'.format(n)[::-1], 2)"
|
Array in python with arbitrary index,"[100, None, None, None, None, None, None, None, None, None, 200]"
|
Best way to encode tuples with json,"simplejson.dumps(dict([('%d,%d' % k, v) for k, v in list(d.items())]))"
|
Convert list of tuples to list?,list(chain.from_iterable(a))
|
writing string to a file on a new line everytime?,f.write('text to write\n')
|
Get models ordered by an attribute that belongs to its OneToOne model,User.objects.order_by('-pet__age')[:10]
|
Select everything but a list of columns from pandas dataframe,df[df.columns - ['T1_V6']]
|
How do I sort a Python list of time values?,"sorted([tuple(map(int, d.split(':'))) for d in my_time_list])"
|
How to subset a data frame using Pandas based on a group criteria?,df.groupby('User')['X'].filter(lambda x: x.sum() == 0)
|
Parsing non-zero padded timestamps in Python,"datetime.strptime('2015/01/01 12:12am', '%Y/%m/%d %I:%M%p')"
|
Python Recursive Search of Dict with Nested Keys,"_get_recursive_results(d, ['l', 'm'], ['k', 'stuff'])"
|
Removing white space from txt with python,"re.sub('\\s{2,}', '|', line.strip())"
|
Drawing a huge graph with networkX and matplotlib,"plt.savefig('graph.png', dpi=1000)"
|
Sending a file over TCP sockets in Python,s.send('Hello server!')
|
How do I pipe the output of file to a variable in Python?,"output = Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]"
|
How to attach debugger to a python subproccess?,ForkedPdb().set_trace()
|
Python: Sum values in a dictionary based on condition,sum(v for v in list(d.values()) if v > 0)
|
How to open a file with the standard application?,"os.system('start ""$file""')"
|
Pythonically add header to a csv file,writer.writeheader()
|
Python - Converting Hex to INT/CHAR,[ord(c) for c in s.decode('hex')]
|
How to split a string within a list to create key-value pairs in Python,print(dict([s.split('=') for s in my_list]))
|
pandas - Changing the format of a data frame,"df.groupby(['level_0', 'level_1']).counts.sum().unstack()"
|
What is the proper way to print a nested list with the highest value in Python,"print(max(x, key=sum))"
|
Python: define multiple variables of same type?,"levels = [{}, {}, {}]"
|
adding new key inside a new key and assigning value in python dictionary,dic['Test'].update({'class': {'section': 5}})
|
Scientific notation colorbar in matplotlib,plt.show()
|
MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 OK\r\n\r\n')
|
MITM proxy over SSL hangs on wrap_socket with client,connection.send('HTTP/1.0 200 established\r\n\r\n')
|
Is there a generator version of `string.split()` in Python?,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))"
|
How do I plot multiple X or Y axes in matplotlib?,plt.show()
|
Python: using a dict to speed sorting of a list of tuples,list_dict = {t[0]: t for t in tuple_list}
|
How do I convert a hex triplet to an RGB tuple and back?,"struct.unpack('BBB', rgbstr.decode('hex'))"
|
Split a list into parts based on a set of indexes in Python,"[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16], [17, 18, 19]]"
|
Multiplying values from two different dictionaries together in Python,"dict((k, v * dict2[k]) for k, v in list(dict1.items()) if k in dict2)"
|
How to match beginning of string or character in Python,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.