text
stringlengths
4
1.08k
How to check if a value exists in a dictionary (python),type(iter(d.values()))
Optional get parameters in django?,"url('^so/(?P<required>\\d+)/', include('myapp.required_urls'))"
Consequences of abusing nltk's word_tokenize(sent),"nltk.tokenize.word_tokenize('Hello, world.')"
Getting the total number of lines in a Tkinter Text widget?,int(text_widget.index('end-1c').split('.')[0])
Normalize columns of pandas data frame,df = df / df.max().astype(np.float64)
Python repeat string,print('{0} {0}'.format(s[:5]))
Using Python Regular Expression in Django,"""""""^org/(?P<company_name>\\w+)/$"""""""
find xml element based on its attribute and change its value,"elem.find('.//number[@topic=""sys/phoneNumber/1""]')"
Copying data from S3 to AWS redshift using python and psycopg2,conn.commit()
Python: sorting dictionary of dictionaries,"sorted(dic, key=lambda x: dic[x].get('Fisher', float('inf')))"
Python - json without whitespaces,"json.dumps(separators=(',', ':'))"
How to generate random colors in matplotlib?,plt.show()
Find and replace string values in Python list,"words = [word.replace('[br]', '<br />') for word in words]"
Python Pandas- Merging two data frames based on an index order,df1['cumcount'] = df1.groupby('val1').cumcount()
Print file age in seconds using Python,print('mdatetime = {}'.format(datetime.datetime.fromtimestamp(mtime)))
"python, Json and string indices must be integers, not str",accesstoken = retdict['access_token']
Python: Lambda function in List Comprehensions,[(lambda x: x * i) for i in range(4)]
How to convert SQL Query result to PANDAS Data Structure?,"df = pd.read_sql(sql, cnxn)"
How do I get the name of a python class as a string?,test.__name__
Changing marker style in scatter plot according to third variable,plt.show()
How to find out if there is data to be read from stdin on Windows in Python?,os.isatty(sys.stdin.fileno())
Compare Python Pandas DataFrames for matching rows,"pd.merge(df1, df2, on=common_cols, how='inner')"
Changing time frequency in Pandas Dataframe,"new = df.resample('T', how='mean')"
How to find and count emoticons in a string using python?,wordcount = len(s.split())
"""TypeError: string indices must be integers"" when trying to make 2D array in python","Tablero = array('b', [Boardsize, Boardsize])"
How would I go about playing an alarm sound in python?,os.system('beep')
Python regexp groups: how do I get all groups?,"re.findall('[a-z]+', s)"
"sigmoidal regression with scipy, numpy, python, etc","scipy.optimize.leastsq(residuals, p_guess, args=(x, y))"
"Displaying numbers with ""X"" instead of ""e"" scientific notation in matplotlib",plt.show()
"Resize matrix by repeating copies of it, in python","array([[0, 1, 0, 1, 0, 1, 0], [2, 3, 2, 3, 2, 3, 2]])"
How to decrement a variable while printing in Python?,print(decrement())
efficient way to compress a numpy array (python),"my_array.compress([(x in ['this', 'that']) for x in my_array['job']])"
What's the simplest way of detecting keyboard input in python from the terminal?,"termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)"
How to specify the endiannes directly in the numpy datatype for a 16bit unsigned integer?,"np.memmap('test.bin', dtype=np.dtype('>u2'), mode='r')"
convert list of tuples to multiple lists in Python,"zip(*[(1, 2), (3, 4), (5, 6)])"
Congruency Table in Pandas (Pearson Correlation between each row for every row pair),"df.corr().mask(np.equal.outer(df.index.values, df.columns.values))"
Conditionally passing arbitrary number of default named arguments to a function,"func('arg', 'arg2', 'some value' if condition else None)"
Sending ASCII Command using PySerial,ser.write('open1\r\n')
Python: How to make a list of n numbers and randomly select any number?,random.choice(mylist)
Is there a simple way to change a column of yes/no to 1/0 in a Pandas dataframe?,"pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)"
Iterate a list of tuples,"tuple_list = [(a, some_process(b)) for a, b in tuple_list]"
Python concatenate string & list,""""""", """""".join(str(f) for f in fruits)"
Find index of last occurrence of a substring in a string,s.rfind('l')
How do you select choices in a form using Python?,form['FORM1'] = ['Value1']
Python: Convert unicode string to MM/DD/YYYY,"datetime.datetime.strptime('Mar232012', '%b%d%Y').strftime('%m/%d/%Y')"
How to use symbolic group name using re.findall(),"[{'toto': '1', 'bip': 'xyz'}, {'toto': '15', 'bip': 'abu'}]"
Splitting Numpy array based on value,zeros = np.where(a == 0)[0]
Splitting integer in Python?,[int(i) for i in str(12345)]
How to get the label of a choice in a Django forms ChoiceField?,{{OBJNAME.get_FIELDNAME_display}}
python subprocess with gzip,p.stdin.close()
text with unicode escape sequences to unicode in python,print('test \\u0259'.decode('unicode-escape'))
How do convert unicode escape sequences to unicode characters in a python string,print(name.decode('latin-1'))
How to write unicode strings into a file?,f.write(s)
How can I color Python logging output?,logging.error('some error')
Python Checking a string's first and last character,"print('hi' if str1.startswith('""') and str1.endswith('""') else 'fails')"
Sort order of lists in multidimensional array in Python,"test = sorted(test, key=lambda x: len(x) if type(x) == list else 1)"
Writing to a file in a for loop,text_file.close()
Setting a clip on a seaborn plot,"sns.kdeplot(x=points['x_coord'], y=points['y_coord'], ax=ax)"
How can I build a recursive function in python?,sys.setrecursionlimit()
Vertical text in Tkinter Canvas,root.mainloop()
How to subtract one from every value in a tuple in Python?,"holes = [(table[i][1] + 1, table[i + 1][0] - 1) for i in range(len(table) - 1)]"
Cookies with urllib2 and PyWebKitGtk,opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
Importing a local variable in a function into timeit,time = timeit.timeit(lambda : module.expensive_func(data))
"Python ""extend"" for a dictionary",a.update(b)
Multiplying values from two different dictionaries together in Python,"{k: (v * dict2[k]) for k, v in list(dict1.items()) if k in dict2}"
Python - Return rows after a certain date where a condition is met,df.groupby('deviceid').apply(after_purchase)
Python - dump dict as a json string,json.dumps(fu)
Python - How can I do a string find on a Unicode character that is a variable?,zzz = 'foo'
How to center a window on the screen in Tkinter?,root.title('Not centered')
how to convert a python dict object to a java equivalent object?,"map.put(key, new_value)"
How do I attach event bindings to items on a canvas using Tkinter?,root.mainloop()
How to create a dict with letters as keys in a concise way?,"dic = dict((y, x) for x, y in enumerate(al, 1))"
How to retrieve table names in a mysql database with Python and MySQLdb?,cursor.execute('USE mydatabase')
How do you count cars in OpenCV with Python?,img = cv2.imread('parking_lot.jpg')
What's a quick one-liner to remove empty lines from a python string?,text = os.linesep.join([s for s in text.splitlines() if s])
Importing financial data into Python Pandas using read_csv,"data.loc[0, 'transaction_amount']"
Split a list into nested lists on a value,"[[1, 4], [6, 9], [3, 9, 4]]"
How do I raise the same Exception with a custom message in Python?,print(' got error of type ' + str(type(e)) + ' with message ' + e.message)
convert integer to binary,"your_list = map(int, '{:b}'.format(your_int))"
"Python-Matplotlib boxplot. How to show percentiles 0,10,25,50,75,90 and 100?",plt.show()
How to get the values from a NumPy array using multiple indices,"arr[[1, 4, 5]]"
Is there a way to split a string by every nth separator in Python?,"print(['-'.join(words[i:i + span]) for i in range(0, len(words), span)])"
What are the guidelines to allow customizable logging from a Python module?,logger = logging.getLogger(__name__)
Dynamically add subplots in matplotlib with more than one column,fig.tight_layout()
Python regex alternative for join,"re.sub('(?<=.)(?=.)', '-', string)"
CherryPy interferes with Twisted shutting down on Windows,cherrypy.engine.start()
Move a tkinter canvas with Mouse,root.mainloop()
How to convert integer value to array of four bytes in python,"map(ord, tuple(struct.pack('!I', number)))"
Remove column from multi index dataframe,df.columns = pd.MultiIndex.from_tuples(df.columns.to_series())
Extract external contour or silhouette of image in Python,"contour(im, levels=[245], colors='black', origin='image')"
Remove items from a list while iterating,somelist[:] = [x for x in somelist if not determine(x)]
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))}
Reading tab delimited csv into numpy array with different data types,"np.genfromtxt(txt, delimiter='\t', dtype='6int,S20')"
Is it possible to have multiple statements in a python lambda expression?,"(lambda x, f: list(y[1] for y in f(x)))(lst, lambda x: (sorted(y) for y in x))"
How can I do a batch insert into an Oracle database using Python?,connection.commit()
Python: how to calculate the sum of a list without creating the whole list first?,sum(a)
How do I match zero or more brackets in python regex,"re.sub('\\[.*\\]|\\{.*\\}', '', one)"
How to set pdb break condition from within source code?,pdb.set_trace()
How to check if a python module exists without importing it,imp.find_module('eggs')
how to move identical elements in numpy array into subarrays,"np.split(a, np.nonzero(np.diff(a))[0] + 1)"