text
stringlengths
4
1.08k
trim whitespaces (including tabs) in string `s`,"print(re.sub('[\\s+]', '', s))"
relevance of typename in namedtuple,"Point = namedtuple('whatsmypurpose', ['x', 'y'], verbose=True)"
getting unique foreign keys in django?,"farms = qs.values_list('farm', flat=True).distinct()"
regular expression to find any number in a string,nums.search('0001.20000').group(0)
reading multiple csv files into python pandas dataframe,"frame = pd.read_csv(path, names=columns)"
how to iterate over dataframe and generate a new dataframe,"df2 = df[~pd.isnull(df.L)].loc[:, (['P', 'L'])].set_index('P')"
matplotlib 3d scatter plot with colorbar,"ax.scatter(xs, ys, zs, c=cs, marker=m)"
django: how to filter users that belong to a specific group,"qs = User.objects.filter(groups__name__in=['foo', 'bar'])"
persistent terminal session in python,"subprocess.call(['/bin/bash', '-c', '/bin/echo $HOME'])"
correct code to remove the vowels from a string in python,""""""""""""".join([x for x in c if x not in vowels])"
save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`,"plt.savefig('filename.png', dpi=300)"
stop infinite page load in selenium webdriver - python,driver.get('http://www.example.com')
how to determine a numpy-array reshape strategy,"np.einsum('ijk,kj->i', A, B)"
passing a function with two arguments to filter() in python,"list(filter(functools.partial(get_long, treshold=13), DNA_list))"
convert dictionaries into string python,""""""", """""".join('{} {}'.format(k, v) for k, v in list(d.items()))"
regex to remove periods in acronyms?,"re.sub('(?<!\\w)([A-Z])\\.', '\\1', s)"
"is it ok to raise a built-in exception, but with a different message, in python?",raise ValueError('invalid input encoding')
how to account for accent characters for regex in python?,"hashtags = re.findall('#(\\w+)', str1, re.UNICODE)"
how to convert a numpy 2d array with object dtype to a regular 2d array of floats,"np.array(arr[:, (1)], dtype=np.float)"
how can i transform blocks into a blockdiagonal matrix (numpy),"r = np.kron(np.diag([1, 2, 3]), np.ones((3, 3), dtype='int'))"
how to refine a mesh in python quickly,"np.array([(arr + i) for i in np.arange(-0.2, 0.25, 0.1)]).T.ravel()"
convert a column of list in series `s` to dummies,pd.get_dummies(s.apply(pd.Series).stack()).sum(level=0)
removing the label from django's textarea widget,"comment = forms.CharField(label='', help_text='', widget=forms.Textarea())"
django urlsafe base64 decode string `uenc` with decryption,base64.urlsafe_b64decode(uenc.encode('ascii'))
python requests multipart http post,"requests.post(url, headers=headers, data=data, files=files)"
simple way to append a pandas series with same index,"pd.concat([a, b], ignore_index=True)"
is it possible to have multiple statements in a python lambda expression?,"[heapq.nsmallest(x, 2)[1] for x in list_of_lists]"
map two lists into a dictionary in python,"new_dict = dict(zip(keys, values))"
"insert a list into another list, without brackets and by replacing the current item in that index","[2, 6, 8, 7, 9, 6, 5, 4, 2]"
how do i disable log messages from the requests library?,logging.getLogger('requests').setLevel(logging.WARNING)
how to split a string into integers in python?,"map(int, '42 0'.split())"
importing a local variable in a function into timeit,time = timeit.timeit(lambda : module.expensive_func(data))
"matplotlib subplot title, figure title formatting",plt.subplots_adjust(top=0.75)
how to convert this list into a dictionary,"{'pigeon': '1', 'hate': '10', 'hello': '10', 'would': '5', 'adore': '10'}"
list of all unique characters in a string?,""""""""""""".join(set('aaabcabccd'))"
live output from subprocess command,"proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)"
convert a 1d array to a 2d array in numpy,"new = np.reshape(a, (-1, ncols))"
create a list containing all cartesian products of elements in list `a`,list(itertools.product(*a))
find tuple in list of tuples `a_list` with the largest second element,"max(a_list, key=operator.itemgetter(1))"
builder pattern equivalent in python,return ''.join('Hello({})'.format(i) for i in range(100))
how to run a function/thread in a different terminal window in python?,proc.wait()
how can one replace an element with text in lxml?,"print(etree.tostring(f, pretty_print=True))"
encoding a string to ascii,"s = s.decode('some_encoding').encode('ascii', 'replace')"
index confusion in numpy arrays,"B = numpy.array([A[0, 0, 1], A[2, 1, 2]])"
how do i set color to rectangle in matplotlib?,plt.show()
remove strings from a list that contains numbers in python,[x for x in my_list if not any(c.isdigit() for c in x)]
how do i use a relative path in a python module when the cwd has changed?,package_directory = os.path.dirname(os.path.abspath(__file__))
how to parse django templates for template tags,"""""""{% *url +[^']"""""""
convert csv file 'test.csv' into two-dimensional matrix,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)"
read csv file 'myfile.csv' into array,"df = pd.read_csv('myfile.csv', sep=',', header=None)"
sum of every two columns in pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')"
get a list of locally installed python modules,help('modules')
create pandas dataframe from txt file with specific pattern,"df['Region Name'] = df['Region Name'].str.replace(' \\(.+$', '')"
write a tuple of tuples `a` to a csv file using python,writer.writerow(A)
manipulating binary data in python,print(repr(data))
creating list of random numbers in python,print('%.5f' % randomList[index])
drop all columns in dataframe `df` that holds a maximum value bigger than 0,df.columns[df.max() > 0]
how to use current logged in user as pk for django detailview?,return self.request.user
python: how to get attribute of attribute of an object with getattr?,"getattr(getattr(myobject, 'id', None), 'number', None)"
block mean of numpy 2d array,"a = a.reshape((a.shape[0], -1, n))"
how do i display current time using python + django?,now = datetime.datetime.now().strftime('%H:%M:%S')
how to replace the nth element of multi dimension lists in python?,"a = [['0', '0'], ['0', '0'], ['0', '0']]"
python : reverse order of list,"lines.sort(key=itemgetter(2), reverse=True)"
how to pass argparse arguments to a class,args = parser.parse_args()
how to get one number specific times in an array python,[0] * 3
"check if 3 is not in the list [4,5,6]","(3 not in [4, 5, 6])"
how do i use matplotlib autopct?,plt.show()
how can i convert this string to list of lists?,"ast.literal_eval('[(0,0,0), (0,0,1), (1,1,0)]')"
"what's the most pythonic way to merge 2 dictionaries, but make the values the average values?",[d[key] for d in dicts if key in d]
"convert a dataframe `df`'s column `id` into datetime, after removing the first and last 3 letters",pd.to_datetime(df.ID.str[1:-3])
print file age in seconds using python,print(os.path.getmtime('/tmp'))
get often occuring string patterns from column in r or python,"[('okay', 5), ('bla', 5)]"
convert all strings in a list to int,"results = list(map(int, results))"
forcing python version in windows,sys.exit(1)
python: pass a generic dictionary as a command line arguments,"{'bob': '1', 'ben': '3', 'sue': '2'}"
count occurrences of certain words in pandas dataframe,df.words.str.contains('he').sum()
find string with regular expression in python,print(url.split('/')[-1].split('.')[0])
print the concatenation of the digits of two numbers in python,print(str(2) + str(1))
terminating qthread gracefully on qdialog reject(),time.sleep(0.5)
updating the x-axis values using matplotlib animation,plt.show()
how to find row of 2d array in 3d numpy array,"array([[True, True], [False, False], [False, False], [True, True]], dtype=bool)"
decode url-encoded string `some_string` to its character equivalents,urllib.parse.unquote(urllib.parse.unquote(some_string))
sqlalchemy many-to-many performance,all_challenges = session.query(Challenge).join(Challenge.attempts).all()
"in python, how does one test if a string-like object is mutable?","isinstance(s, str)"
"check if 3 is not in a list [2, 3, 4]","(3 not in [2, 3, 4])"
turning a string into list of positive and negative numbers,"[int(el) for el in inputstring.split(',')]"
add pandas column values in a for loop?,test['label'] = test['name'].apply(lambda x: my_function(x))
convert utf-8 with bom to utf-8 with no bom in python,u = s.decode('utf-8-sig')
how to print current date on python3?,print(datetime.datetime.now().strftime('%y'))
conditional replacement of row's values in pandas dataframe,df.groupby('ID').cumcount() + 1
matplotlib axis labels: how to find out where they will be located?,plt.show()
build a dataframe with columns from tuple of arrays,"pd.DataFrame(np.vstack(someTuple).T, columns=['birdType', 'birdCount'])"
python: slicing a multi-dimensional array,"slice = [arr[i][0:2] for i in range(0, 2)]"
how to signal slots in a gui from a different process?,app.exec_()
pandas intersect multiple series based on index,"pd.concat(series_list, axis=1)"
how to create a spinning command line cursor using python?,sys.stdout.write('\x08')
loop for each item in a list,"itertools.product(mydict['item1'], mydict['item2'])"
is it possible to get widget settings in tkinter?,root = Tk()
"is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?","keys, values = zip(*list(d.items()))"
change log level dynamically to 'debug' without restarting the application,logging.getLogger().setLevel(logging.DEBUG)