text
stringlengths 4
1.08k
|
|---|
Order of operations in a dictionary comprehension,my_dict = {x[0]: x[1:] for x in my_list}
|
Draw a line correlating zones between multiple subplots in matplotlib,plt.show()
|
Get the indexes of truthy elements of a boolean list as a list/tuple,"[i for i, elem in enumerate(bool_list, 1) if elem]"
|
How can I split a string into tokens?,"['x', '+', '13.5', '*', '10', 'x', '-', '4', 'e', '1']"
|
How can I insert data into a MySQL database?,db.commit()
|
How can I split this comma-delimited string in Python?,"print(s.split(','))"
|
Get the string within brackets in Python,"m = re.search('\\[(\\w+)\\]', s)"
|
Sum the second value of each tuple in a list,sum(x[1] for x in structure)
|
Replace a string in list of lists,"example = [[x.replace('\r\n', '') for x in i] for i in example]"
|
Most Pythonic way to fit a variable to a range?,"result = min(max_value, max(min_value, result))"
|
how connect to vertica using pyodbc,conn = pyodbc.connect('DSN=VerticaDB1;UID=dbadmin;PWD=mypassword')
|
How to sort/ group a Pandas data frame by class label or any specific column,df.sort_index()
|
How to load a pickle file containing a dictionary with unicode characters?,"pickle.load(open('/tmp/test.pkl', 'rb'))"
|
python pandas extract unique dates from time series,df['Date'][0].date()
|
Declaring a multi dimensional dictionary in python,new_dict['key1']['key2'] += 5
|
A list as a key for PySpark's reduceByKey,"rdd.map(lambda k_v: (tuple(k_v[0]), k_v[1])).groupByKey()"
|
How do I fill two (or more) numpy arrays from a single iterable of tuples?,"arr.sort(order=['f0', 'f1'])"
|
How to gracefully fallback to `NaN` value while reading integers from a CSV with Pandas?,"df = pd.read_csv('my.csv', na_values=['n/a'])"
|
Subtract all items in a list against each other,"[(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)]"
|
Python: passing a function with parameters as parameter,func(*args)
|
How to modify elements of iterables with iterators? I.e. how to get write-iterators in Python?,"[[1, 2, 5], [3, 4, 5]]"
|
How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+a)+b+', mystring)"
|
Showing the stack trace from a running Python application,"os.kill(pid, signal.SIGUSR1)"
|
Disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False)
|
how to clear/delete the Textbox in tkinter python on Ubuntu,"tex.delete('1.0', END)"
|
Split a list of tuples into sub-lists of the same tuple field,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]"
|
"How to check if all values of a dictionary are 0, in Python?",all(value == 0 for value in list(your_dict.values()))
|
"Annoying white space in bar chart (matplotlib, Python)",plt.show()
|
finding duplicates in a list of lists,"sorted(map(list, list(totals.items())))"
|
How to remove lines in a Matplotlib plot,"pylab.setp(_self.ax.get_yticklabels(), fontsize=8)"
|
Adding alpha channel to RGB array using numpy,"numpy.dstack((your_input_array, numpy.zeros((25, 54))))"
|
How do I create a histogram from a hashmap in python?,plt.show()
|
Django - include app urls,__init__.py
|
how to get the index of dictionary with the highest value in a list of dictionary,"max(lst, key=lambda x: x['score'])"
|
How to slice a list of strings with space delimiter?,new_list = [x.split()[-1] for x in Original_List]
|
Get the immediate minimum among a list of numbers in python,min([x for x in num_list if x > 2])
|
Duplicating some rows and changing some values in pandas,"pd.concat([good, new], axis=0, ignore_index=True)"
|
How to create a function that outputs a matplotlib figure?,plt.show()
|
How to convert a hex string to hex number,print(hex(new_int)[2:])
|
python http request with token,"requests.get('https://www.mysite.com/', auth=('username', 'pwd'))"
|
Pythonic way to get the largest item in a list,"max_item = max(a_list, key=operator.itemgetter(1))"
|
How to convert 'binary string' to normal string in Python3?,"""""""a string"""""".decode('ascii')"
|
Python sorting - A list of objects,"sorted(L, key=operator.itemgetter('resultType'))"
|
How to unquote a urlencoded unicode string in python?,urllib.parse.unquote(url).decode('utf8')
|
"Difference between using commas, concatenation, and string formatters in Python","print('I am printing {} and {}'.format(x, y))"
|
"Difference between using commas, concatenation, and string formatters in Python","print('I am printing {0} and {1}'.format(x, y))"
|
Python Pandas Pivot Table,"df.pivot_table('Y', rows='X', cols='X2')"
|
"In Django, how do I clear a sessionkey?",del request.session['mykey']
|
Call Perl script from Python,"subprocess.call(['/usr/bin/perl', './uireplace.pl', var])"
|
Python requests library how to pass Authorization header with single token,"r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})"
|
Pandas DataFrame Groupby two columns and get counts,"df.groupby(['col5', 'col2']).size().groupby(level=1).max()"
|
"Python ""extend"" for a dictionary",a.update(b)
|
Append string to the start of each value in a said column of a pandas dataframe (elegantly),df['col'] = 'str' + df['col'].astype(str)
|
Get output of python script from within python script,print(proc.communicate()[0])
|
Pandas - replacing column values,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)"
|
removing data from a numpy.array,a[a != 0]
|
beautifulsoup can't find href in file using regular expression,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))"
|
How to execute a command prompt command from python,os.system('dir c:\\')
|
Sort list with multiple criteria in python,"['0.0.0.0.py', '1.0.0.0.py', '1.1.0.0.py']"
|
How to change plot background color?,ax.patch.set_facecolor('black')
|
"In python, how do I cast a class object to a dict",dict(my_object)
|
Sum of Every Two Columns in Pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')"
|
Open a text file using notepad as a help file in python?,webbrowser.open('file.txt')
|
how to read a file in other directory in python,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')"
|
How to calculate percentage of sparsity for a numpy array/matrix?,np.prod(a.shape)
|
Show the final y-axis value of each line with matplotlib,plt.show()
|
How to use lxml to find an element by text?,"e = root.xpath('.//a[contains(text(),""TEXT A"")]')"
|
How to use lxml to find an element by text?,"e = root.xpath('.//a[starts-with(text(),""TEXT A"")]')"
|
Update all models at once in Django,Model.objects.all().order_by('some_field').update(position=F(some_field) + 1)
|
What is the most pythonic way to avoid specifying the same value in a string,"""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')"
|
Case insensitive dictionary search with Python,theset = set(k.lower() for k in thedict)
|
Floating Point in Python,print('%.3f' % 4.53)
|
Converting a List of Tuples into a Dict in Python,"{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}"
|
Merging a list with a list of lists,[a[x].append(b[x]) for x in range(3)]
|
"How to write list of strings to file, adding newlines?","data.write('%s%s\n' % (c, n))"
|
Elegant way to convert list to hex string,"hex(sum(b << i for i, b in enumerate(reversed(walls))))"
|
Matplotlib - How to plot a high resolution graph?,"plt.savefig('filename.png', dpi=300)"
|
Python: find out whether a list of integers is coherent,"return my_list == list(range(my_list[0], my_list[-1] + 1))"
|
Is there any lib for python that will get me the synonyms of a word?,"['dog', 'domestic_dog', 'Canis_familiaris']"
|
How do I use a dictionary to update fields in Django models?,Book.objects.filter(pk=pk).update(**d)
|
How to rearrange Pandas column sequence?,"['a', 'b', 'x', 'y']"
|
Using MultipartPostHandler to POST form-data with Python,print(urllib.request.urlopen(request).read())
|
How can I use python finding particular json value by key?,"['cccc', 'aaa', 'ss']"
|
How to initialize a two-dimensional array in Python?,[[Foo() for x in range(10)] for y in range(10)]
|
I want to plot perpendicular vectors in Python,ax.set_aspect('equal')
|
Convert a String representation of a Dictionary to a dictionary?,"ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")"
|
Convert a String representation of a Dictionary to a dictionary?,"ast.literal_eval(""shutil.rmtree('mongo')"")"
|
How can I check if a date is the same day as datetime.today()?,yourdatetime.date() < datetime.today().date()
|
Finding the most frequent character in a string,print(collections.Counter(s).most_common(1)[0])
|
Flattening a list of NumPy arrays?,np.concatenate(input_list).ravel().tolist()
|
Scikit-learn: How to run KMeans on a one-dimensional array?,"km.fit(x.reshape(-1, 1))"
|
Interweaving two numpy arrays,"array([1, 2, 3, 4, 5, 6])"
|
How to use matplotlib tight layout with Figure?,plt.show()
|
Sorting or Finding Max Value by the second element in a nested list. Python,"max(alkaline_earth_values, key=lambda x: x[1])"
|
How to change the 'tag' when logging to syslog from 'Unknown'?,log.info('FooBar')
|
Using a comparator function to sort,"sorted(subjects, operator.itemgetter(0), reverse=True)"
|
Python Matplotlib - Impose shape dimensions with Imsave,"plt.figure(figsize=(1, 1))"
|
Double-decoding unicode in python,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
|
using python logging in multiple modules,"logger.debug('My message with %s', 'variable data')"
|
"How to reverse geocode serverside with python, json and google maps?",jsondata['results'][0]['address_components']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.