text
stringlengths
4
1.08k
Convert Average of Python List Values to Another List,"{'Mike': [[1, 4], [5, 7]], 'Joe': [[5, 7], [6, 9], [7, 4]]}"
Can I set user-defined variable in Python MySQLdb?,cursor.execute('SELECT @X:=@X+1 FROM some_table')
Using Spritesheets in Tkinter,self.canvas.pack()
Matplotlib fill beetwen multiple lines,"plt.fill_between(X, Y2, Y3, color='m', alpha=0.5)"
Creating a game board with Python and Tkinter,root.mainloop()
Matplotlib - Contour plot with single value,plt.show()
How to order a list of lists by the first value,"[1, 1, 1] < [1, 1, 2]"
Slice pandas DataFrame where column's value exists in another array,df.query('a in @keys')
"In Python, how to change text after it's printed?",sys.stdout.flush()
Reshape pandas dataframe from rows to columns,"pd.concat([df2[df2.Name == 'Jane'].T, df2[df2.Name == 'Joe'].T])"
Find closest row of DataFrame to given time in Pandas,df.iloc[i]
Algorithm - How to delete duplicate elements in a list efficiently?,M = list(set(L))
Get rows that have the same value across its columns in pandas,"df[df.apply(lambda x: min(x) == max(x), 1)]"
run program in Python shell,"exec(compile(open('C:\\test.py').read(), 'C:\\test.py', 'exec'))"
Is it possible to make POST request in Flask?,app.run(debug=True)
"Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","zip(my_list, map(my_dictionary.get, my_list))"
Condensing Multiple List Comprehensions,"[[9, 30, 'am'], [5, 0, 'pm']]"
Django: Convert a POST request parameters to query string,request.META['QUERY_STRING']
Numpy: get 1D array as 2D array without reshape,"np.column_stack([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])"
Python Logging - Disable logging from imported modules,logger = logging.getLogger(__name__)
Fastest way to store large files in Python,"gzip.GzipFile('output file name', 'wb')"
Split a string only by first space in python,"s.split(' ', 1)"
Sorting list by an attribute that can be None,my_list.sort(key=nonesorter)
Remove certain keys from a dictionary in python,"FieldSet = dict((k, v) for k, v in FieldSet.items() if len(v) != 1)"
Importing files in Python from __init__.py,__init__.py
How to check if value is nan in unittest?,assertTrue(math.isnan(nan_value))
Counting the amount of occurences in a list of tuples,"sum(v for k, v in c.items() if v > 1)"
Sending binary data over sockets with Python,s.send(my_bytes)
Python: plot data from a txt file,pylab.show()
replace values in an array,"np.place(a, np.isnan(a), 0)"
Find the nth occurrence of substring in a string,"find_nth('foofoofoofoo', 'foofoo', 2)"
How to get text with selenium web driver in python,element = driver.find_element_by_class_name('class_name').text
How to export a table to csv or excel format,writer.writerows(cursor.fetchall())
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')"
Numpy - add row to array,"array([[0, 1, 2], [0, 2, 0], [0, 1, 2], [1, 2, 0], [2, 1, 2]])"
How can I vectorize the averaging of 2x2 sub-arrays of numpy array?,y.mean(axis=1).mean(axis=-1)
pandas: slice a MultiIndex by range of secondary index,s['b'].iloc[1:10]
Using Python to add a list of files into a zip file,"ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)"
How do I write output in same place on the console?,sys.stdout.flush()
How to update matplotlib's imshow() window interactively?,draw()
How to modify matplotlib legend after it has been created?,pylab.show()
How to count the occurrence of certain item in an ndarray in Python?,"a = numpy.array([0, 3, 0, 1, 0, 1, 2, 1, 0, 0, 0, 0, 1, 3, 4])
collections.Counter(a)"
How to use Python kazoo library?,from kazoo.client import KazooClient
python replace backslashes to slashes,"print('pictures\\12761_1.jpg'.replace('\\', '/'))"
How to query MultiIndex index columns values in pandas,"x.loc[(x.B >= 111.0) & (x.B <= 500.0)].set_index(['A', 'B'])"
Passing a function with two arguments to filter() in python,basetwo('10010')
Extracting Data with Python Regular Expressions,"re.findall('\\d+', s)"
Pythonic way to assign the parameter into attribute?,"setattr(self, k, v)"
where to store a log file name in python?,logging.debug('This is a message from another place.')
Reshaping array into a square array Python,"x.reshape(2, 2, 5).transpose(1, 0, 2).reshape(4, 5)"
Convert list to lower-case,l = [item.lower() for item in l]
Best way to remove elements from a list,[item for item in my_list if some_condition()]
get the index of the last negative value in a 2d array per column,"np.maximum.accumulate((A2 < 0)[:, ::-1], axis=1)[:, ::-1]"
How can I execute Python code in a virtualenv from Matlab,system('python myscript.py')
How to union two subqueries in SQLAlchemy and postgresql,session.query(q).limit(10)
Convert numpy array to tuple,tuple([tuple(row) for row in myarray])
Getting the docstring from a function,help(my_func)
Python: How can I run python functions in parallel?,p1.start()
Moving x-axis to the top of a plot in matplotlib,"ax.tick_params(labelbottom='off', labeltop='on')"
Can Selenium web driver have access to javascript global variables?,browser.execute_script('return globalVar;')
Django - Filter objects older than X days,Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days))
How can I convert an RGB image into grayscale in Python?,img.save('greyscale.png')
Adding Values From Tuples of Same Length,"coord = tuple(sum(x) for x in zip(coord, change))"
How do I get the Application ID at runtime,os.environ['APPLICATION_ID']
python: how to sort lists alphabetically with respect to capitalized letters,"sorted(lst, key=lambda L: (L.lower(), L))"
Select everything but a list of columns from pandas dataframe,"df.drop(['T1_V6'], axis=1)"
Is there a function for Converting IP address to decimal number in python?,"print(struct.unpack('!I', socket.inet_aton('127.0.0.1'))[0])"
Python pandas - filter rows after groupby,"get_group_rows(df, 'A', 'B', 'median', '>')"
How do you specify the foreign key column value in SQLAlchemy?,"users = relationship('User', backref='account')"
Perform different operations based on index modulus of list items,"['One', 'TWO', 'eerhT', 'Four', 'FIVE', 'xiS', 'Seven', 'EIGHT', 'eniN']"
How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?,plt.show()
How to get the seconds since epoch from the time + date output of gmtime() in Python?,time.mktime(time.gmtime(0))
How to get absolute url in Pylons?,"print(url('blog', id=123, qualified=True, host='example.com'))"
Replace values in list using Python,new_items = [(x if x % 2 else None) for x in items]
Named colors in matplotlib,plt.show()
How to dynamically select a method call in Python?,"getattr(foo_obj, command)()"
Python requests can't send multiple headers with same key,"headers = [('X-Attribute', 'A'), ('X-Attribute', 'B')]"
Python export csv data into file,"output.write('{0}:{1}\n'.format(nfeature[0] + 1, nfeature[1]))"
"In Python, is there a concise way to use a list comprehension with multiple iterators?","list(itertools.product(list(range(1, 3)), list(range(1, 5))))"
How to parse XML in Python and LXML?,print(doc.xpath('//aws:weather/aws:ob/aws:temp')[0].text)
Convert pandas DataFrame to a nested dict,df = pd.DataFrame.from_dict(data)
Resampling trade data into OHLCV with pandas,"df.resample('30s', how={'volume': 'sum'})"
Reading a CSV file into Pandas Dataframe with invalid characters (accents),sys.setdefaultencoding('utf8')
How to make a histogram from a list of strings in Python?,df.plot(kind='bar')
Notebook widget in Tkinter,root.title('ttk.Notebook')
Convert string to JSON using Python,print(d['glossary']['title'])
Convert SRE_Match object to string,print(result.group(0))
How to execute manage.py from the Python shell,"execute_from_command_line(['manage.py', 'syncdb'])"
Summarizing a dictionary of arrays in Python,"OrderedDict(heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1])))"
Tkinter: Wait for item in queue,time.sleep(1)
How do I make a Django ModelForm menu item selected by default?,form = MyModelForm(instance=someinst)
Can the Python CSV module parse files with multi-column delimiters,"reader = csv.reader(open('test.csv'), delimiter='|#|')"
What is the simplest way to create a shaped window in wxPython?,"self.Bind(wx.EVT_PAINT, self.OnPaint)"
Inserting JSON into MySQL using Python,db.execute('INSERT INTO json_col VALUES (' + json_value + ')')
Is there a scala equivalent to python's list comprehension,list.filter(_ != somevalue)
Make new column in Panda dataframe by adding values from other columns,"df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)"
From a list of lists to a dictionary,{l[1]: l for l in lol}
How to install python packages in virtual environment only with virtualenv bootstrap script?,"subprocess.call(['pip', 'install', '-E', home_dir, 'django'])"
Set variable point size in matplotlib,"ax1.scatter(data[0], data[1], marker='o', c='b', s=data[2], label='the data')"