text
stringlengths 4
1.08k
|
|---|
two dimensional array in python,arr = [[]] * 3
|
python extract data from file,"file = codecs.open(filename, encoding='utf-8')"
|
removing a list of characters in string,"s.translate(None, ',!.;')"
|
python: filter lines from a text file which contain a particular word,[line for line in open('textfile') if 'apple' in line]
|
"trimming a string "" hello """,' Hello '.strip()
|
python - compress ascii string,comptest('')
|
how to convert dictionary into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))"
|
how to use symbolic group name using re.findall(),"[{'toto': '1', 'bip': 'xyz'}, {'toto': '15', 'bip': 'abu'}]"
|
execute a mv command `mv /home/somedir/subdir/* somedir/` in subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)"
|
regex for removing data in parenthesis,"item = re.sub(' \\(\\w+\\)', '', item)"
|
"fix first element, shuffle the rest of a list/array",numpy.random.shuffle(a[1:])
|
convert list of tuples to multiple lists in python,"map(list, zip(*[(1, 2), (3, 4), (5, 6)]))"
|
pandas dataframe select columns in multiindex,"df.loc[:, (slice(None), 'A')]"
|
how can i add textures to my bars and wedges?,pyplot.draw()
|
get complete path of a module named `os`,imp.find_module('os')[1]
|
sorting the content of a dictionary by the value and by the key,"sorted(list(d.items()), key=lambda x: (x[1], x[0]))"
|
"get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values","Counter([1, 2, 2, 2, 3]) - Counter([1, 2])"
|
how to set the font size of a canvas' text item?,"canvas.create_text(x, y, font=('Purisa', 12), text=k)"
|
python 3 and tkinter opening new window by clicking the button,root.mainloop()
|
get count of values associated with key in dict python,sum(d['success'] for d in s)
|
write pdf file from url using urllib2,"FILE = open('report.pdf', 'wb')"
|
select rows from a dataframe based on values in a column in pandas,"print(df.loc[df['B'].isin(['one', 'three'])])"
|
parse a string with a date to a datetime object,"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')"
|
why pandas transform fails if you only have a single column,df.groupby('a')['a'].transform('count')
|
using python to execute a command on every file in a folder,"print(os.path.join(directory, file))"
|
how to draw directed graphs using networkx in python?,"nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)"
|
make a python list constant and uneditable,return my_list[:]
|
run a .bat program in the background on windows,os.startfile('startsim.bat')
|
python regex to match multiple times,"pattern = re.compile('/review: (http://url.com/(\\d+)\\s?)+/', re.IGNORECASE)"
|
iterate over dictionary `d` in ascending order of values,"sorted(iter(d.items()), key=lambda x: x[1])"
|
how can i join a list into a string (caveat)?,"print(""that's interesting"".encode('string_escape'))"
|
convert 173 to binary string,bin(173)
|
modify a data frame column with list comprehension,"df = pd.DataFrame(['some', 'short', 'string', 'has', 'foo'], columns=['col1'])"
|
how to round to two decimal places in python 2.7?,Decimal('33.505').quantize(Decimal('0.01'))
|
getting column values from multi index data frame pandas,"df.loc[df.xs('Panning', axis=1, level=1).eq('Panning').any(1)]"
|
joining a list that has integer values with python,""""""", """""".join(map(str, myList))"
|
upload file with python mechanize,"br.form.add_file(open(filename), 'text/plain', filename)"
|
get a list of substrings consisting of the first 5 characters of every string in list `buckets`,[s[:5] for s in buckets]
|
how do i offset lines in matplotlib by x points,plt.show()
|
extracting all rows from pandas dataframe that have certain value in a specific column,data[data['Value'] == True]
|
how to execute a file within the python interpreter?,"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))"
|
sorting a graph by its edge weight. python,"lst.sort(key=lambda x: (-x[2], x[0]))"
|
find all occurrences of a substring in a string,"[m.start() for m in re.finditer('test', 'test test test test')]"
|
python pandas: multiple aggregations of the same column,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})"
|
group multi-index pandas dataframe,"s.groupby(level=['first', 'second']).sum()"
|
python cherrypy - how to add header,cherrypy.quickstart(Root())
|
dump json into yaml,"json.dump(data, outfile, ensure_ascii=False)"
|
python/matplotlib - is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')"
|
how to deal with settingwithcopywarning in pandas?,"df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 1, 2, 2]})"
|
split string `s` by letter 's',s.split('s')
|
efficient way to count the element in a dictionary in python using a loop,{x[0]: len(list(x[1])) for x in itertools.groupby(sorted(mylist))}
|
how to use opencv (python) to blur faces?,"cv2.imwrite('./result.png', result_image)"
|
how to re.sub() a optional matching group using regex in python?,"re.sub('url((?:#[0-9]+)?)', 'new_url\\1', test2)"
|
how to show matplotlib plots in python,plt.show()
|
python: intersection indices numpy array,"numpy.nonzero(numpy.in1d(a, b))"
|
how to extract first two characters from string using regex,"df.c_contofficeID.str.replace('^12', '').to_frame()"
|
django can't find url pattern,"url('^$', include('sms.urls')),"
|
select multiple ranges of columns in pandas dataframe,"df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]"
|
selecting from multi-index pandas,"df.xs(1, level='A', drop_level=False)"
|
3d plots using maplot3d from matplotlib-,plt.show()
|
how to make print statement one line in python?,"print('If a hippo ways 2000 pounds, gives birth to a 100 pound calf and then eats a 50 pound meal how much does she weigh?')"
|
"trimming a string "" hello """,' Hello '.strip()
|
numpy: how to vectorize parameters of a functional form of a function applied to a data set,"np.einsum('ij,jk->ik', nodes, x ** np.array([2, 1, 0])[:, (None)])"
|
how to print string in this way,"re.sub('(.{6})', '\\1#', str)"
|
converting string lists `s` to float list,"floats = map(float, s.split())"
|
url encoding in python,urllib.parse.quote(s.encode('utf-8'))
|
python get last 5 elements in list of lists,print(list(itertools.chain(*[l for l in lst if l is not None]))[-5:])
|
select all text in a textbox selenium rc using ctrl + a,element.click()
|
call a function with argument list `args`,func(*args)
|
converting hex string `s` to its integer representations,[ord(c) for c in s.decode('hex')]
|
replace comma in string `s` with empty string '',"s = s.replace(',', '')"
|
how do i plot multiple x or y axes in matplotlib?,plt.subplots_adjust(bottom=0.2)
|
how to base64 encode a pdf file in python,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')"
|
convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns,"df.pivot(index='order', columns='sample')"
|
pandas changing cell values based on another cell,b = df[(df['time'] > X) & (df['time'] < Y)]
|
how to slice and extend a 2d numpy array?,"array([[1, 2], [7, 8], [3, 4], [9, 10], [5, 6], [11, 12]])"
|
efficient distance calculation between n points and a reference in numpy/scipy,"np.sqrt(np.sum((a - b) ** 2, axis=1))"
|
list of non-zero elements in a list in python,b = [int(i != 0) for i in a]
|
create a set from string `s` to remove duplicate characters,print(' '.join(set(s)))
|
how can i multiply all items in a list together with python?,"from functools import reduce
|
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])"
|
how can i find the missing value more concisely?,"z, = set(('a', 'b', 'c')) - set((x, y))"
|
can python dictionary comprehension be used to create a dictionary of substrings and their locations?,"d = collections.defaultdict(lambda : [0, []])"
|
convert bytes string `s` to an unsigned integer,"struct.unpack('>q', s)[0]"
|
sorting a list of lists of dictionaries in python,key = lambda x: sum(y['play'] for y in x)
|
how to plot arbitrary markers on a pandas data series?,ts.plot(marker='o')
|
how can i use executemany to instert into mysql a list of dictionaries in python,conn.rollback()
|
transform comma separated string into a list but ignore comma in quotes,"['1', '', '2', '3,4']"
|
get name of primary field of django model,CustomPK._meta.pk.name
|
how do i build a numpy array from a generator?,my_array = numpy.array(list(gimme()))
|
how to put parameterized sql query into variable and then execute in python?,"cursor.execute(sql_and_params[0], sql_and_params[1:])"
|
"remove a substring "".com"" from the end of string `url`","print(url.replace('.com', ''))"
|
pythonic implementation of quiet / verbose flag for functions,logging.basicConfig(level=logging.INFO)
|
remove the string value `item` from a list of strings `my_sequence`,[item for item in my_sequence if item != 'item']
|
converting year and day of year into datetime index in pandas,"pd.to_datetime(df['year'] * 1000 + df['doy'], format='%Y%j')"
|
how to scrape a website that requires login first with python,print(br.open('https://github.com/settings/emails').read())
|
how to insert the contents of one list into another,"array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']"
|
using python regular expression in django,"""""""^org/(?P<company_name>\\w+)/$"""""""
|
how to access a dictionary key value present inside a list?,print(L[1]['d'])
|
python pandas: apply a function with arguments to a series,"my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.