text
stringlengths
4
1.08k
"remove trailing newline in string ""test string\n""",'test string\n'.rstrip()
how can i solve system of linear equations in sympy?,"linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))"
construct pandas dataframe from list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])"
print a character that has unicode value `\u25b2`,print('\u25b2'.encode('utf-8'))
python spliting a string,"a, b = 'string_without_spaces'.split(' ', 1)"
set variable point size in matplotlib,"ax1.scatter(data[0], data[1], marker='o', c='b', s=data[2], label='the data')"
python requests: post json and file in single request,"r = requests.post(url, files=files, data=data, headers=headers)"
run app `app` on host '192.168.0.58' and port 9000 in flask,"app.run(host='192.168.0.58', port=9000, debug=False)"
how can i select random characters in a pythonic way?,random.choice(string.ascii_letters + string.digits)
python: how to count overlapping occurrences of a substring,"len([s.start() for s in re.finditer('(?=aa)', 'aaa')])"
python pandas: apply a function with arguments to a series. update,"a['x'].apply(lambda x, y: x + y, args=(100,))"
how do i translate a iso 8601 datetime string into a python datetime object?,yourdate = dateutil.parser.parse(datestring)
python - how can i do a string find on a unicode character that is a variable?,"ast.literal_eval(""u'"" + zzz + ""'"")"
how do i do a not equal in django queryset filtering?,Entry.objects.filter(~Q(id=3))
print numbers in list `list` with precision of 3 decimal places,"print('[%s]' % ', '.join('%.3f' % val for val in list))"
how to combine the data from many data frames into a single data frame with an array as the data values,"p.apply(np.sum, axis='major')"
how to add a new column to a csv file using python?,writer.writerows(all)
how to edit model data using django forms,"form = MyModelForm(request.POST, instance=my_record)"
opencv video saving in python,cv2.destroyAllWindows()
pandas: create another column while splitting each row from the first column,"df['new_column'] = df['old_column'].apply(lambda x: '#' + x.replace(' ', ''))"
converting integer `num` to list,[int(x) for x in str(num)]
how to make python gracefully fail?,sys.exit(main())
multiplication of 1d arrays in numpy,"np.dot(np.atleast_2d(a).T, np.atleast_2d(b))"
sqlite3 in python,c.execute('SELECT * FROM tbl')
convert python datetime to epoch with strftime,"datetime.datetime(2012, 4, 1, 0, 0).timestamp()"
divide two lists in python,"[(x * 1.0 / y) for x, y in zip(a, b)]"
sort dict by value python,"sorted(list(data.items()), key=lambda x: x[1])"
simple way of creating a 2d array with random numbers (python),[[random.random() for i in range(N)] for j in range(N)]
how to extract all upper from a string? python,""""""""""""".join(c for c in s if c.isupper())"
get column name where value is something in pandas dataframe,"df_result = pd.DataFrame(ts, columns=['value'])"
how can i convert a url query string into a list of tuples using python?,"[('foo', 'bar'), ('key', 'val')]"
sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)"
python: most efficient way to convert date to datetime,"datetime(date.year, date.month, date.day)"
get the tuple in list `a_list` that has the largest item in the second index,"max_item = max(a_list, key=operator.itemgetter(1))"
switching keys and values in a dictionary in python,"my_dict2 = dict((y, x) for x, y in my_dict.items())"
how to get tuples from lists using list comprehension in python,"[(lst[i], lst2[i]) for i in range(len(lst))]"
how can i append this elements to an array in python?,"['1', '2', '3', '4', 'a', 'b', 'c', 'd']"
get os name,"import platform
platform.system()"
how to write a tuple of tuples to a csv file using python,writer.writerows(A)
"python, remove all occurrences of string in list",new_array = [x for x in main_array if x not in second_array]
"how to change [1,2,3,4] to '1234' using python",""""""""""""".join(map(str, [1, 2, 3, 4]))"
python - sum 4d array,M.sum(axis=0).sum(axis=0)
how to get a value from every column in a numpy matrix,(M == 0).T.nonzero()
how to generate negative random value in python,"random.uniform(-1, 1)"
read hdf5 file to pandas dataframe with conditions,"pd.read_hdf('/tmp/out.h5', 'results_table', where='A in [1,3,4]')"
finding the index of elements based on a condition using python list comprehension,[i for i in range(len(a)) if a[i] > 2]
extract date from a string 'monkey 2010-07-32 love banana',"dparser.parse('monkey 2010-07-32 love banana', fuzzy=True)"
convert a flat list to list of list in python,"[['a', 'b', 'c'], ['d', 'e', 'f']]"
upload file with python mechanize,"br.form.add_file(open(filename), 'text/plain', filename)"
"selenium `driver` click a hyperlink with the pattern ""a[href^='javascript']""","driver.find_element_by_css_selector(""a[href^='javascript']"").click()"
how to implement jump in pygame without sprites?,pygame.display.flip()
superscript in python plots,plt.show()
how to read the file contents from a file?,"input = open(fullpath, 'rb')"
get the indices in array `b` of each element appearing in array `a`,"np.in1d(b, a).nonzero()[0]"
python: how to act on re's matched string,"re.sub('(\\d+)', lambda m: '%.0f' % (float(m.group(1)) * 2), 'test line 123')"
find average of every three columns in pandas dataframe,"pd.concat([df, res], axis=1)"
deploy flask app as windows service,app.run()
interleave the elements of two lists `a` and `b`,"[j for i in zip(a, b) for j in i]"
python: a4 size for a plot,"rc('figure', figsize=(11.69, 8.27))"
how to export a table to csv or excel format,writer.writerows(cursor.fetchall())
how to perform double sort inside an array?,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)"
python: how to add three text files into one variable and then split it into a list,"msglist = [hextotal[i:i + 4096] for i in range(0, len(hextotal), 4096)]"
python requests not working with google app engine,"r = http.request('GET', 'https://www.23andme.com/')"
get a list of all keys from dictionary `dicta` where the number of occurrences of value `duck` in that key is more than `1`,"[k for k, v in dictA.items() if v.count('duck') > 1]"
get last day of the month `month` in year `year`,"calendar.monthrange(year, month)[1]"
concatenate an arbitrary number of lists in a function in python,"join_lists([1, 2, 3], [4, 5, 6])"
sort a numpy array according to 2nd column only if values in 1st column are same,"a[np.lexsort(a[:, ::-1].T)]"
how can i get all the plain text from a website with scrapy?,xpath('//body//text()').extract()
how to remove all characters before a specific character in python?,"re.sub('.*I', 'I', stri)"
why i can't convert a list of str to a list of floats?,"C = row[1].split(',')[1:-1]"
how to filter model results for multiple values for a many to many field in django,"Group.objects.filter(player__name__in=['Player1', 'Player2'])"
python - return rows after a certain date where a condition is met,df.groupby('deviceid').apply(after_purchase)
python logging: use milliseconds in time format,"logging.Formatter(fmt='%(asctime)s.%(msecs)03d', datefmt='%Y-%m-%d,%H:%M:%S')"
assigning string with boolean expression,openmode = 'w'
sort a numpy array like a table,"array([[2, 1], [5, 1], [0, 3], [4, 5]])"
"calling an external command ""some_command < input_file | another_command > output_file""",os.system('some_command < input_file | another_command > output_file')
how to use `numpy.savez` in a loop for save more than one array?,"np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])"
generate list of numbers in specific format,[('%.2d' % i) for i in range(16)]
non-consuming regular expression split in python,"re.split('(?<=[\\.\\?!]) ', text)"
using a global dictionary with threads in python,global_dict['bar'] = 'hello'
printing a list of numbers in python v.3,"print('\t'.join(map(str, [1, 2, 3, 4, 5])))"
extract first column from a multi-dimensional array `a`,[row[0] for row in a]
plot histogram of datetime.time python / matplotlib,plt.show()
change user agent for selenium driver,driver.execute_script('return navigator.userAgent')
check if a directory exists in a zip file with python,any(x.startswith('%s/' % name.rstrip('/')) for x in z.namelist())
convert a list of dictionaries `listofdict into a dictionary of dictionaries,"dict((d['name'], d) for d in listofdict)"
sort list `xs` in ascending order of length of elements,"xs.sort(lambda x, y: cmp(len(x), len(y)))"
search for string `blabla` in txt file 'example.txt',"datafile = file('example.txt')
found = False
for line in datafile:
if (blabla in line):
return True
return False"
how to change legend size with matplotlib.pyplot,"plot.legend(loc=2, prop={'size': 6})"
encode unicode string '\xc5\xc4\xd6' to utf-8 code,print('\xc5\xc4\xd6'.encode('UTF8'))
join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])"
python del if in dictionary in one line,"myDict.pop(key, None)"
get a list of strings `split_text` with fixed chunk size `n` from a string `the_list`,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]"
python pandas extract unique dates from time series,df['Date'][0]