text
stringlengths
4
1.08k
How to binarize the values in a pandas DataFrame?,"pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order]"
How do I implement a null coalescing operator in SQLAlchemy?,session.query(Task).filter(Task.time_spent > timedelta(hours=3)).all()
Python Nested List Comprehension with two Lists,[(x + y) for x in l2 for y in l1]
append tuples to a list,"[['AAAA', 1.11], ['BBB', 2.22], ['CCCC', 3.33]]"
Numpy: Get random set of rows from 2D array,"A[(np.random.randint(A.shape[0], size=2)), :]"
Django - accessing the RequestContext from within a custom filter,TEMPLATE_CONTEXT_PROCESSORS += 'django.core.context_processors.request'
Adding a 1-D Array to a 3-D array in Numpy,"np.zeros((6, 9, 20)) + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).reshape((1, 9, 1))"
swap values in a tuple/list inside a list in python?,"map(lambda t: (t[1], t[0]), mylist)"
User defined legend in python,plt.show()
Simple way to append a pandas series with same index,"pd.concat([a, b], ignore_index=True)"
How can I select 'last business day of the month' in Pandas?,"pd.date_range('1/1/2014', periods=12, freq='BM')"
Sorting by multiple conditions in python,table.sort(key=lambda t: t.points)
Print string as hex literal python,"""""""ABC"""""".encode('hex')"
How to check if all elements in a tuple or list are in another?,"all(i in (1, 2, 3, 4, 5) for i in (1, 6))"
Select multiple ranges of columns in Pandas DataFrame,"df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]"
Finding the index of an item given a list containing it in Python,"[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo']"
improved sprintf for PHP,"printf('Hello %1$s. Your %1$s has just been created!', 'world')"
python tkinter how to bind key to a button,"master.bind('s', self.sharpen)"
How to compile a string of Python code into a module whose functions can be called?,foo()
How to convert a tuple to a string in Python?,[item[0] for item in queryresult]
How do I plot a step function with Matplotlib in Python?,plt.show()
How to disable input to a Text widget but allow programatic input?,"text_widget.bind('<1>', lambda event: text_widget.focus_set())"
How to perform element-wise multiplication of two lists in Python?,"[(a * b) for a, b in zip(lista, listb)]"
extract item from list of dictionaries,[d for d in a if d['name'] == 'pluto']
numpy matrix vector multiplication,"np.einsum('ji,i->j', a, b)"
Index 2D numpy array by a 2D array of indices without loops,"array([[0, 0], [1, 1], [2, 2]])"
Converting hex to int in python,ord('\xff')
Extracting all rows from pandas Dataframe that have certain value in a specific column,data[data['Value'] == True]
How to create a simple network connection in Python?,server.serve_forever()
"Converting an array of integers to a ""vector""","mapping = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]])"
Finding missing values in a numpy array,numpy.nonzero(m.mask)
Reading in integer from stdin in Python,n = int(input())
How to remove a key from a python dictionary?,"my_dict.pop('key', None)"
Motif search with Gibbs sampler,Motifs.append(Motif)
Dealing with spaces in Flask url creation,"{'south_carolina': 'SC', 'north_carolina': 'NC'}"
How to Calculate Centroid in python,"nx.mean(data[:, -3:], axis=0)"
How to remove square bracket from pandas dataframe,df['value'] = df['value'].str.strip('[]')
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?,"open('ComponentReport-DJI.xls', 'rb').read(200)"
How to start a background process in Python?,"subprocess.Popen(['rm', '-r', 'some.file'])"
Splitting comma delimited strings in python,"split_at('obj<1, 2, 3>, x(4, 5), ""msg, with comma""', ',')"
How to loop backwards in python?,"range(10, 0, -1)"
Get the first element of each tuple in a list in Python,res_list = [x[0] for x in rows]
Adding errorbars to 3D plot in matplotlib,plt.show()
How to fill a polygon with a custom hatch in matplotlib?,plt.show()
Python max length of j-th item across sublists of a list,"[max(len(a), len(b)) for a, b in zip(*x)]"
Passing a list of strings from Python to Rust,"['blah', 'blah', 'blah', 'blah']"
Python: Merge two lists of dictionaries,"[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]"
Python values of multiple lists in one list comprehension,"zip(list(range(10)), list(range(10, 0, -1)))"
Get a list of values from a list of dictionaries in python,[d['key'] for d in l if 'key' in d]
Pandas: Create new dataframe that averages duplicates from another dataframe,"df.groupby(level=0, axis=1).mean()"
How can I split a string into tokens?,"['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', '1']"
Matplotlib boxplot without outliers,"boxplot([1, 2, 3, 4, 5, 10], showfliers=False)"
How can I check the data transfer on a network interface in python?,time.sleep(5)
get index of character in python list,"['a', 'b'].index('b')"
How to do a regex replace with matching case?,"re.sub('\\bfoo\\b', cased_replacer('bar'), 'this is Foo', flags=re.I)"
Nest a flat list based on an arbitrary criterion,"[['tie', 'hat'], ['Shoes', 'pants', 'shirt'], ['jacket']]"
Python - how to refer to relative paths of resources when working with code repository,"fn = os.path.join(os.path.dirname(__file__), 'my_file')"
How can I get around declaring an unused variable in a for loop?,[''] * len(myList)
"How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+)([A-Z])', '20M10000N80M')"
"How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+|[A-Z])', '20M10000N80M')"
Parsing a tweet to extract hashtags into an array in Python,"re.findall('#(\\w+)', 'http://example.org/#comments')"
Removing entries from a dictionary based on values,"{k: v for k, v in list(hand.items()) if v}"
How to design code in Python?,duck.quack()
Python: find the first mismatch in two lists,"next((idx, x, y) for idx, (x, y) in enumerate(zip(list1, list2)) if x != y)"
How to repeat Pandas data frame?,"pd.concat([x] * 5, ignore_index=True)"
How do I read the first line of a string?,my_string.splitlines()[0]
How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]"
How do you run a complex sql script within a python program?,os.system('mysql < etc')
Sorting a list of lists of dictionaries in python,"key = lambda x: sum(map(itemgetter('play'), x))"
Group by multiple time units in pandas data frame,dfts.groupby(lambda x: x.month).mean()
numpy matrix multiplication,(a.T * b).T
How to save an image using django imageField?,request.FILES['image']
Python random sequence with seed,"['list', 'elements', 'go', 'here']"
How to get the original variable name of variable passed to a function,"['e', '1000', 'c']"
Capturing emoticons using regular expression in python,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)"
Python - sum values in dictionary,sum(item['gold'] for item in example_list)
passing variables to a template on a redirect in python,self.redirect('/sucess')
Python tuple trailing comma syntax rule,"a = ['a', 'bc']"
How to make pylab.savefig() save image for 'maximized' window instead of default size,"plt.savefig('myplot.png', dpi=100)"
Linear regression with pymc3 and belief,"pymc3.traceplot(trace, vars=['alpha', 'beta', 'sigma'])"
Python: Converting from ISO-8859-1/latin1 to UTF-8,apple.decode('iso-8859-1').encode('utf8')
Pandas (python): How to add column to dataframe for index?,"df['new_col'] = list(range(1, len(df) + 1))"
How to get num results in mysqldb,"self.cursor.execute(""SELECT COUNT(*) FROM table WHERE asset_type='movie'"")"
"Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)","[key for item in lst for key, value in list(my_dict.items()) if item in value]"
Repeating elements in list comprehension,"[y for x in range(3) for y in [x, x]]"
Python Convert String Literal to Float,"total = sum(float(item) for item in s.split(','))"
JSON to pandas DataFrame,pd.read_json(elevations)
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 in python to split a string with unknown number of spaces as separator?,""""""" 1234 Q-24 2010-11-29 563 abc a6G47er15"""""".split()"
How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+((', 'z', '+', '88', '))']]"
How to position and align a matplotlib figure legend?,plt.show()
Sorting list by an attribute that can be None,mylist.sort(key=lambda x: Min if x is None else x)
Scrolling down a page with Selenium Webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')"
How to properly split this list of strings?,"[['z', '+', '2', '-', '44'], ['4', '+', '55', '+', 'z', '+', '88']]"
How to generate unique equal hash for equal dictionaries?,hash(pformat(a)) == hash(pformat(b))
Splitting a string into a list (but not separating adjacent numbers) in Python,"re.findall('\\d+|\\S', string)"
Applying a dictionary of string replacements to a list of strings,"['I own half bottle', 'Give me three quarters of the profit']"
How to check if all values in the columns of a numpy matrix are the same?,"np.all(a == a[(0), :], axis=0)"
Appending the same string to a list of strings in Python,"['foobar', 'fobbar', 'fazbar', 'funkbar']"
How to place minor ticks on symlog scale?,plt.show()