text
stringlengths
4
1.08k
how to make a set of lists,set(tuple(i) for i in l)
matplotlib: -- how to show all digits on ticks?,plt.gca().xaxis.set_major_formatter(FixedFormatter(ll))
sorting a list of tuples in python,"sorted([(1, 3), (3, 2), (2, 1)], key=itemgetter(1))"
how do i translate a iso 8601 datetime string into a python datetime object?,"datetime.datetime.strptime(conformed_timestamp, '%Y%m%dT%H%M%S.%f%z')"
how to query multiindex index columns values in pandas,df.query('0 < A < 4 and 150 < B < 400')
send data 'http/1.0 200 ok\r\n\r\n' to socket `connection`,connection.send('HTTP/1.0 200 established\r\n\r\n')
get keys and items of dictionary `d`,list(d.items())
what's a good way to combinate through a set?,"print(list(powerset([4, 5, 6])))"
pandas - rolling up rows to fill in missing data,"df.groupby('name')[['id', 'email']].first()"
find all occurrences of integer within text in python,"print(sum(sum(map(int, r.findall(line))) for line in data))"
how to remove gaps between subplots in matplotlib?,"fig.subplots_adjust(wspace=0, hspace=0)"
counting unique words in python,print(len(set(w.lower() for w in open('filename.dat').read().split())))
how can i draw a bezier curve using python's pil?,im.save('out.png')
selecting specific rows and columns from numpy array,"a[[[0, 0], [1, 1], [3, 3]], [[0, 2], [0, 2], [0, 2]]]"
configure url in django properly,"url('^', include('sms.urls')),"
convert a datetime string back to a datetime object of format '%y-%m-%d %h:%m:%s.%f',"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')"
how to print/show an expression in rational number form in python,print('\n\x1b[4m' + '3' + '\x1b[0m' + '\n2')
append 4 to list `foo`,foo.append(4)
replace non-ascii characters with a single space,return ''.join([(i if ord(i) < 128 else ' ') for i in text])
how to get the index with the key in python dictionary?,list(x.keys()).index('c')
efficient way to shift a list in python,"shift([1, 2, 3], 14)"
pyplot: show only first 3 lines in legend,plt.show()
merge 2 dataframes with same values in a column,df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue'])
i want to use matplotlib to make a 3d plot given a z function,plt.show()
how can i add an additional row and column to an array?,"L = [[1, 2, 3], [4, 5, 6]]"
python: how to find common values in three lists,"set(a).intersection(b, c)"
split a string at a certain index,"re.split('(?<=\\))\\.', '(1.2).2')"
splitting a string into 2-letter segments,"re.findall('.{1,2}', s, re.DOTALL)"
"get the text of multiple elements found by xpath ""//*[@type='submit']/@value""","browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text"
pandas dataframe groupby datetime month,df.groupby(pd.TimeGrouper(freq='M'))
getting values from json using python,data['lat']
how to use numpy.random.choice in a list of tuples?,"lista_elegir[np.random.choice(len(lista_elegir), 1, p=probabilit)]"
retrieve all items in an numpy array 'x' except the item of the index 1,"x[(np.arange(x.shape[0]) != 1), :, :]"
print string including multiple variables `name` and `score`,"print(('Total score for', name, 'is', score))"
python: split string by list of separators,"[s.strip() for s in re.split(',|;', string)]"
string split formatting in python 3,s.split()
lambda in python,"(lambda x, y: x + y)(1, 2)"
find the index of sub string 's' in string `str` starting from index 11,"str.find('s', 11)"
"unescape special characters without splitting data in array of strings `['i ', u'<', '3s u ', u'&', ' you luvz me']`",""""""""""""".join(['I ', '<', '3s U ', '&', ' you luvz me'])"
how can i create the empty json object in python,"json.loads(request.POST.get('mydata', '{}'))"
python plot horizontal line for a range of values,plt.show()
"how to create argument of type ""list of pairs"" with argparse?","p.add_argument('--sizes', type=pair, nargs='+')"
find average of a nested list `a`,a = [(sum(x) / len(x)) for x in zip(*a)]
summing the second item in a list of lists of lists,[sum([x[1] for x in i]) for i in data]
matplotlib: how to change data points color based on some variable,plt.show()
pandas groupby range of values,"df.groupby(pd.cut(df['B'], np.arange(0, 1.0 + 0.155, 0.155))).sum()"
how to get the sum of timedelta in python?,"datetime.combine(date.today(), time()) + timedelta(hours=2)"
django models selecting single field,"Employees.objects.values_list('eng_name', 'rank')"
drop column based on a string condition,"df.drop([col for col in df.columns if 'chair' in col], axis=1, inplace=True)"
sending json request with python,"r = requests.get('http://myserver/emoncms2/api/post', data=payload)"
converting a string to list in python,"""""""0,1,2"""""".split(',')"
check if a local variable `myvar` exists,('myVar' in locals())
split string `a` using new-line character '\n' as separator,a.rstrip().split('\n')
float64 with pandas to_csv,"df.to_csv('pandasfile.csv', float_format='%g')"
how to plot events on time on using matplotlib,plt.show()
is there a matplotlib equivalent of matlab's datacursormode?,plt.figure()
how to i get scons to invoke an external script?,"env.PDF('document.pdf', 'document.tex')"
get the list with the highest sum value in list `x`,"print(max(x, key=sum))"
write column 'sum' of dataframe `a` to csv file 'test.csv',"a.to_csv('test.csv', cols=['sum'])"
how to check the existence of a row in sqlite with python?,"cursor.execute('create table components (rowid int,name varchar(50))')"
pandas dataframe to sqlite,"df = pd.DataFrame({'TestData': [1, 2, 3, 4, 5, 6, 7, 8, 9]}, dtype='float')"
how to download to a specific directory with python?,"urllib.request.urlretrieve('http://python.org/images/python-logo.gif', '/tmp/foo.gif')"
how do you reverse the significant bits of an integer in python?,"return int(bin(x)[2:].zfill(32)[::-1], 2)"
get the first element of each tuple in a list in python,[x[0] for x in rows]
how to sort a python dict by value,"res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))"
parsing html page using beautifulsoup,print(''.join([str(t).strip() for t in x.findAll(text=True)]))
create list of single item repeated n times in python,"itertools.repeat(0, 10)"
use of findall and parenthesis in python,[s[0] for s in formula.split('+')]
how do i extract the names from a simple function?,"['foo.bar', 'foo.baz']"
"in python 2.4, how can i execute external commands with csh instead of bash?",os.system('echo $SHELL')
how to disable the window maximize icon using pyqt4?,win.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
using chromedriver with selenium/python/ubuntu,driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')
pandas: how to change all the values of a column?,df['Date'] = df['Date'].apply(convert_to_year)
how can i get python to use upper case letters to print hex values?,print('0x%X' % value)
read file `fname` line by line into a list `content`,"with open(fname) as f:
content = f.readlines()"
replace non-ascii characters with a single space,"re.sub('[^\\x00-\\x7F]+', ' ', text)"
make a window `root` jump to the front,"root.attributes('-topmost', True)"
get key by value in dictionary with same value in python?,"print([key for key, value in d.items() if value == 1])"
count all elements in a nested dictionary `food_colors`,sum(len(v) for v in food_colors.values())
create a tuple from a string and a list of strings,my_tuple = tuple([my_string] + my_list)
how can i compare two lists in python and return matches,set(a) & set(b)
convert datetime object to a string of date only in python,dt.strftime('%m/%d/%Y')
how can i generalize my pandas data grouping to more than 3 dimensions?,"df2.xs('b', axis=1, level=1)"
how to render an ordered dictionary in django templates?,"return render(request, 'main.html', {'context': ord_dict})"
named colors in matplotlib,plt.show()
count lower case characters in a string,return sum(1 for c in string if c.islower())
test a boolean expression in a python string,eval('20<30')
find element by text with xpath in elementtree,"print(doc.xpath('//element[text()=""A""]')[0].tag)"
"i need to convert a string to a list in python 3, how would i do this?",l = ast.literal_eval(s)
customize ticks for axesimage?,"ax.set_xticklabels(['a', 'b', 'c', 'd'])"
getting the first item item in a many-to-many relation in django,Group.objects.get(id=1).members.all()[0]
kill a process `make.exe` from python script on windows,os.system('taskkill /im make.exe')
"add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`","default_data.update({'item4': 4, 'item5': 5, })"
how do i change the range of the x-axis with datetimes in matplotlib?,"ax.set_ylim([0, 5])"
applying uppercase to a column in pandas dataframe,"df['1/2 ID'].apply(lambda x: x.upper(), inplace=True)"
saving a numpy array as an image,"scipy.misc.imsave('outfile.jpg', image_array)"
convert average of python list values to another list,"[([k] + [(sum(x) / float(len(x))) for x in zip(*v)]) for k, v in list(d.items())]"
remove strings containing only white spaces from list,l = [x for x in l if x.strip()]
python string representation of binary data,binascii.hexlify('\r\x9eq\xce')