text
stringlengths
4
1.08k
how do you run a complex sql script within a python program?,os.system('mysql < etc')
how to create a manhattan plot with matplotlib in python?,plt.show()
how can i turn 000000000001 into 1?,int('08')
url decode utf-8 in python,urllib.parse.unquote(url).decode('utf8')
parsing a tweet to extract hashtags into an array in python,"re.findall('#(\\w+)', 'http://example.org/#comments')"
pandas: how can i use the apply() function for a single column?,df['a'] = df['a'].apply(lambda x: x + 1)
indexing a pandas dataframe by integer,df2 = df.reset_index()
how to import modules in google app engine?,"sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))"
create a tree data using networkx in python,"G = nx.balanced_tree(10, 10)"
scatterplot with xerr and yerr with matplotlib,plt.show()
how to sort the letters in a string alphabetically in python,""""""""""""".join(sorted(a))"
combine multiple heatmaps in matplotlib,plt.show()
two combination lists from one list,"print([l[i:i + n] for i in range(len(l)) for n in range(1, len(l) - i + 1)])"
converting datetime.date to utc timestamp in python,timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
how to close a tkinter window by pressing a button?,"button = Button(frame, text='Good-bye.', command=window.destroy)"
how to use bash variables inside a python code?,"subprocess.call(['echo $var'], shell=True)"
fastest way to count number of occurrences in a python list,"[('1', 6), ('2', 4), ('7', 3), ('10', 2)]"
calling a .py script from a specific file path in python interpreter,"exec(compile(open('C:\\X\\Y\\Z').read(), 'C:\\X\\Y\\Z', 'exec'))"
string replace python,"newString = re.sub('\\boldword\\b', 'newword', oldString)"
"calling an external command ""ls""","p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print(line, end=' ')
retval = p.wait()"
proper use of mutexes in python,p.start()
is there a python equivalent to ruby's string interpolation?,print('Who lives in a Pineapple under the sea? {name!s}.'.format(**locals()))
all possible permutations of a set of lists in python,list(itertools.product(*s))
tuple digits to number conversion,float('{0}.{1}'.format(*a))
"calling an external command ""some_command with args""",stream = os.popen('some_command with args')
sort two dimensional list python,"sorted(a, key=foo)"
set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`,"count.setdefault('a', 0)"
how to add unicode character before a string? [python],print(type(word.decode('utf-8')))
"delete an element ""hello"" from a dictionary `lol`",lol.pop('hello')
how to find all possible sequences of elements in a list?,"map(list, permutations([2, 3, 4]))"
python how to sort this list?,"sorted(lst, reverse=True, key=operator.itemgetter(0))"
using pyserial is it possble to wait for data?,"cmd('ATZ', serial.Serial('/dev/ttyUSB0', timeout=1, baudrate=115000))"
how to get current import paths in python?,print(sys.path)
fastest way to sort multiple lists - python,"zip(*sorted(zip(x, y), key=ig0))"
how can i print over the current line in a command line application?,sys.stdout.write('\r')
how to count all elements in a nested dictionary?,sum(len(v) for v in food_colors.values())
"check whether a numpy array `a` contains a given row `[1, 2]`","any(np.equal(a, [1, 2]).all(1))"
flask logging with foreman,app.logger.setLevel(logging.DEBUG)
create a dataframe `d` filled with zeros with indices from 0 to length of `data` and column names from `feature_list`,"d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)"
accessing elements of python dictionary,print(list(sampleDict.values())[0].keys()[0])
select everything but a list of columns from pandas dataframe,"df.drop(['T1_V6'], axis=1)"
convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe,pd.to_datetime(pd.Series(date_stngs))
scalar multiply matrix `a` by `b`,(a.T * b).T
filter queryset for all objects in django model `mymodel` where texts length are greater than `254`,MyModel.objects.filter(text__regex='^.{254}.*')
"python, print delimited list","print(','.join(str(x) for x in a))"
"finding the index of an item 'foo' given a list `['foo', 'bar', 'baz']` containing it","[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']"
faster convolution of probability density functions in python,"convolve_many([[0.6, 0.3, 0.1], [0.5, 0.4, 0.1], [0.3, 0.7], [1.0]])"
how to make two markers share the same label in the legend using matplotlib?,ax.set_title('Custom legend')
"create new list by taking first item from first list, and last item from second list","[value for pair in zip(a, b[::-1]) for value in pair]"
how to return index of a sorted list?,"sorted(list(range(len(s))), key=lambda k: s[k])"
customize x-axis in matplotlib,plt.xlabel('Hours')
how to create a user in django?,"return render(request, 'home.html')"
python pandas - removing rows from a dataframe based on a previously obtained subset,grouped = df.groupby(df['zip'].isin(keep))
how to add multiple values to a dictionary key in python?,"a.setdefault('somekey', []).append('bob')"
prevent delete in django model,self.save()
splitting comma delimited strings in python,"split_at('obj<1, 2, 3>, x(4, 5), ""msg, with comma""', ',')"
double-decoding unicode in python,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
swapping columns in a numpy array?,"my_array[:, ([0, 1])] = my_array[:, ([1, 0])]"
how to split string with limit by the end in python,"""""""hello.world.foo.bar"""""".rsplit('.', 1)"
how do i clone a django model instance object and save it to the database?,obj.save()
"append values `[3, 4]` to a set `a`","a.update([3, 4])"
change the font size on plot `matplotlib` to 22,matplotlib.rcParams.update({'font.size': 22})
pythonic way to insert every 2 elements in a string,"""""""-"""""".join(s[i:i + 2] for i in range(0, len(s), 2))"
"python, find out that a list does not have specific item","3 not in [1, 2, 'a']"
scroll a to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')"
how to close a tkinter window by pressing a button?,window.destroy()
filter items in a python dictionary where keys contain a specific string,"filtered_dict = {k: v for k, v in list(d.items()) if filter_string in k}"
create a list of tuples with adjacent list elements if a condition is true,"[(myList[i - 1], myList[i]) for i in range(len(myList)) if myList[i] == 9]"
how to check if a variable is an integer or a string?,value.isdigit()
best way to randomize a list of strings in python,""""""""""""".join([str(w) for w in random.sample(item, len(item))])"
how to start daemon process from python on windows?,"subprocess.Popen(executable, creationflags=DETACHED_PROCESS, close_fds=True)"
"find ""one letter that appears twice"" in a string","[i[0] for i in re.findall('(([a-z])\\2)', 'abbbbcppq')]"
sort a dictionary `y` by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)"
python - use list as function parameters,some_func(*params)
python convert list to dictionary,"l = ['a', 'b', 'c', 'd', 'e']"
how to specify date format when using pandas.to_csv?,"df.to_csv(filename, date_format='%Y%m%d')"
concatenate all rows of a numpy matrix in python,a.ravel()
find the column name which has the maximum value for each row,df.idxmax(axis=1)
"how do i read a midi file, change its instrument, and write it back?","s.write('midi', '/Users/cuthbert/Desktop/newfilename.mid')"
sort a dictionary `data` by its values,sorted(data.values())
adding custom fields to users in django,uinfo.save()
"split string `s` into a list of strings based on ',' then replace empty strings with zero",""""""","""""".join(x or '0' for x in s.split(','))"
how to execute a python script file with an argument from inside another python script file,"sys.exit(main(sys.argv[1], sys.argv[2]))"
select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`,df.loc[~df['column_name'].isin(some_values)]
how do i format a string using a dictionary in python-3.x?,"""""""foo is {foo}, bar is {bar} and baz is {baz}"""""".format(**d)"
how can i convert this string to list of lists?,"ast.literal_eval('[[0,0,0], [0,0,1], [1,1,0]]')"
replace substring in a list of string,"['hanks sir', 'Oh thanks to remember']"
reshape pandas dataframe from rows to columns,df2[df2.Name == 'Joe'].T
make a list of integers from 0 to `5` where each second element is a duplicate of the previous element,"print([u for v in [[i, i] for i in range(5)] for u in v])"
split elements of a list in python,"[i.split('\t', 1)[0] for i in l]"
how to get the cumulative sum of numpy array in-place,"np.cumsum(a, axis=1, out=a)"
create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york',"[value for key, value in list(programs.items()) if 'new york' in key.lower()]"
convert list of dictionaries to dataframe,pd.DataFrame(d)
extract all keys from a list of dictionaries,set([i for s in [list(d.keys()) for d in LoD] for i in s])
sort values and return list of keys from dict python,"sorted(d, key=d.get)"
convert tab-delimited txt file into a csv file using python,"list(csv.reader(open('demo.txt', 'r'), delimiter='\t'))"
how to set the default color cycle for all subplots with matplotlib?,plt.show()