text
stringlengths
4
1.08k
sum of digits in a string,return sum(int(x) for x in digit if x.isdigit())
"python: dictionary to string, custom format?","""""""<br/>"""""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])"
how can i reverse parts of sentence in python?,return ' '.join(word[::-1] for word in sentence.split())
how can i set the aspect ratio in matplotlib?,fig.savefig('axAspect.png')
what is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')]
connect points with same value in python matplotlib,plt.show()
removing list of words from a string,""""""" """""".join([x for x in query.split() if x.lower() not in stopwords])"
python matplotlib multiple bars,plt.show()
how to shift a string to right in python?,l[-1:] + l[:-1]
reading utf-8 characters from a gzip file in python,"gzip.open('file.gz', 'rt', encoding='utf-8')"
python how do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))"
formatting numbers consistently in python,print('%.1e' % x)
coordinates of item on numpy array,ii = np.where(a == 4)
format numbers to strings in python,"'%02d:%02d:%02d' % (hours, minutes, seconds)"
setting different bar color in matplotlib python,plt.show()
how to declare an array in python,a = [0] * 10000
how to set environment variables in python,os.environ['DEBUSSY'] = '1'
conditional replacement of row's values in pandas dataframe,df['SEQ'] = df.sort_values(by='START').groupby('ID').cumcount() + 1
formatting a pivot table in python,"pd.DataFrame({'X': X, 'Y': Y, 'Z': Z}).T"
most efficient way to create an array of cos and sin in numpy,"return np.vstack((np.cos(theta), np.sin(theta))).T"
how to write a list to xlsx using openpyxl,cell.value = statN
pulling a random word/string from a line in a text file in python,print(random.choice(open('WordsForGames.txt').readline().split()))
python pandas datetime.time - datetime.time,(df[0] - df[1]).apply(lambda x: x.astype('timedelta64[us]'))
how do i sum values in a column that match a given condition using pandas?,"df.loc[df['a'] == 1, 'b'].sum()"
handle wrongly encoded character in python unicode string,some_unicode_string.encode('utf-8')
divide the values of two dictionaries in python,"dict((k, float(d2[k]) / d1[k]) for k in d2)"
how to sort my paws?,data_slices.sort(key=lambda s: s[-1].start)
iterate over a dictionary `dict` in sorted order,return iter(sorted(dict.items()))
how to merge two python dictionaries in a single expression?,c = dict(list(a.items()) | list(b.items()))
find a file in python,"return os.path.join(root, name)"
how to redirect 'print' output to a file using python?,f.write('whatever')
compare values of two arrays in python,"f([3, 2, 5, 4], [2, 3, 2])"
terminate process `p`,p.terminate()
remove cancelling rows from pandas dataframe,"df2 = df.groupby(['customer', 'invoice_nr', 'date']).sum()"
downloading file to specified location with selenium and python,driver.find_element_by_partial_link_text('DEV.tgz').click()
hash unicode string in python,hashlib.sha1(s.encode('utf-8'))
python list comprehensions splitting loop variable,"[(x[1], x[2]) for x in (x.split(';') for x in a.split('\n')) if x[1] != 5]"
django datetime issues (default=datetime.now()),"date = models.DateTimeField(default=datetime.now, blank=True)"
python: mysqldb. how to get columns name without executing select * in a big table?,cursor.execute('SELECT * FROM table_name LIMIT 1')
numpy: get 1d array as 2d array without reshape,"array([[0, 0, 1, 2, 3, 4, 0, 1, 2, 3], [1, 5, 6, 7, 8, 9, 4, 5, 6, 7]])"
how to convert a list into a pandas dataframe,"df = pd.DataFrame({'col1': x, 'col2': y, 'col3': z})"
recursive pattern in regex,"regex.findall('{((?>[^{}]+|(?R))*)}', '{1, {2, 3}} {4, 5}')"
change current working directory in python,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
scroll to the bottom of a web page using selenium webdriver,"driver.execute_script('window.scrollTo(0, Y)')"
produce a pivot table as dataframe using column 'y' in datafram `df` to form the axes of the resulting dataframe,"df.pivot_table('Y', rows='X', cols='X2')"
get the sum of values associated with the key 'success' for a list of dictionaries `s`,sum(d['success'] for d in s)
how to shorten this if and elif code in python,('NORTH ' if b > 0 else 'SOUTH ') + ('EAST' if a > 0 else 'WEST')
python sort list of lists over multiple levels and with a custom order,"my_list.sort(key=lambda x: (order.index(x[0]), x[2], x[3]))"
convert binary string '0b0010101010' to integer,"int('0b0010101010', 2)"
how to retrive get vars in python bottle app,request.query['city']
numpy object arrays,"print(numpy.array([X()], dtype=object))"
how to delete the last row of data of a pandas dataframe,dfrm.drop(dfrm.index[len(dfrm) - 1])
how to change the layout of a gtk application on fullscreen?,gtk.main()
"pandas dataframe, how do i split a column into two","df['A'], df['B'] = df['AB'].str.split(' ', 1).str"
flask jsonify a list of objects,return jsonify(my_list_of_eqtls)
unpack a list in python?,function_that_needs_strings(*my_list)
add x and y labels to a pandas plot,ax.set_ylabel('y label')
how do you set up a flask application with sqlalchemy for testing?,app.run()
python convert decimal to hex,print([hex(x) for x in numbers])
python: intersection indices numpy array,"numpy.in1d(a, b).nonzero()"
string manipulation in cython,"re.sub(' +', ' ', s)"
tensorflow strings: what they are and how to work with them,"x = tf.constant(['This is a string', 'This is another string'])"
convert list to tuple in python,tuple(l)
how to combine two columns with an if/else in python pandas?,"df['year'] = df['year'].where(source_years != 0, df['year'])"
using pytz to convert from a known timezone to local,(local_dt - datetime.datetime.utcfromtimestamp(timestamp)).seconds
python: get number of items from list(sequence) with certain condition,sum(i % 4 == 3 for i in l)
mails not being sent to people in cc,"s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string())"
"how to see traceback on xmlrpc server, not client?",server.serve_forever()
python/matplotlib - is there a way to make a discontinuous axis?,plt.show()
numpy 2d array: change all values to the right of nans,"arr[np.maximum.accumulate(np.isnan(arr), axis=1)] = np.nan"
how to connect a variable to entry widget?,root.mainloop()
save a list of objects in django,o.save()
read into a bytearray at an offset?,bytearray('\x00\x00\x00\x01\x02\x03\x04\x05\x00\x00')
check if datafram `df` has any nan vlaues,df.isnull().values.any()
what is the best way to get the first item from an iterable matching a condition?,next((x for x in range(10) if x > 3))
create list `instancelist` containing 29 objects of type myclass,instancelist = [MyClass() for i in range(29)]
using beautifulsoup to search html for string,soup.body.findAll(text='Python')
how to make lists distinct?,my_list = list(set(my_list))
prepend the same string to all items in a list,['hello{0}'.format(i) for i in a]
find maximum value of a column and return the corresponding row values using pandas,"df.groupby(['country', 'place'], as_index=False)['value'].max()"
fastest way to find the magnitude (length) squared of a vector field,"np.einsum('...j,...j->...', vf, vf, dtype=np.double)[-1, -1, -1]"
conditional matching in regular expression,"re.findall(rx, st, re.VERBOSE)"
pandas: get the value of the index for a row?,"df.set_index('prod_code', inplace=True)"
how to read the first byte of a subprocess's stdout and then discard the rest in python?,"process = Popen(['mycmd', 'myarg'], stdout=DEVNULL, stderr=DEVNULL)"
numpy: efficiently reading a large array,"a = a.reshape((m, n)).T"
get a list of values from a list of dictionaries in python,[d['key'] for d in l]
how to deal with settingwithcopywarning in pandas?,df[df['A'] > 2]['B'] = new_val
use regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeid` of dataframe `df`,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')"
format date without dash?,"datetime.date(2002, 12, 4).strftime('%Y%m%d')"
element-wise minimum of multiple vectors in numpy,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)"
how can i remove text within parentheses with a regex?,"re.sub('\\([^)]*\\)', '', filename)"
can i put a tuple into an array in python?,list_of_tuples[0][0] = 7
how can i set the aspect ratio in matplotlib?,fig.savefig('force.png')
"in python 2.4, how can i execute external commands with csh instead of bash?",os.system('tcsh your_own_script')
remove newline in string 'mac eol\r','Mac EOL\r'.rstrip('\r\n')
how to get only the last part of a path in python?,os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
not able to print statements with 'apostrophe' in it in python. invalid syntax error,"print(""I am jack's raging bile duct"")"
use xml.etree.elementtree to write out nicely formatted xml files,"print(etree.tostring(root, pretty_print=True))"
sorting numbers in string format with python,keys.sort(key=lambda x: [int(y) for y in x.split('.')])
find the string matches within parenthesis from a string `s` using regex,"m = re.search('\\[(\\w+)\\]', s)"