text
stringlengths
4
1.08k
Equivalent of j in Numpy,1j * np.arange(5)
replacing all regex matches in single line,"re.sub('\\b(this|string)\\b', '<markup>\\1</markup>', 'this is my string')"
Is it possible to use 'else' in a python list comprehension?,"[(a if a else 2) for a in [0, 1, 0, 3]]"
Best way to plot an angle between two lines in Matplotlib,plt.show()
Sort a list based on dictionary values in python?,"sorted(trial_list, key=lambda x: trial_dict[x])"
How do I sum values in a column that match a given condition using pandas?,df.groupby('a')['b'].sum()[1]
Multiprocessing writing to pandas dataframe,"pd.concat(d, ignore_index=True)"
Reshape pandas dataframe from rows to columns,df2.groupby('Name').apply(tgrp)
Getting file size in Python?,os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
Calling a parent class constructor from a child class in python,"super(Instructor, self).__init__(name, year)"
"How do you pick ""x"" number of unique numbers from a list in Python?","random.sample(list(range(1, 16)), 3)"
Best way to strip punctuation from a string in Python,"s.translate(None, string.punctuation)"
Python - Bulk Select then Insert from one DB to another,cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1')
The best way to filter a dictionary in Python,"d = {k: v for k, v in list(d.items()) if v > 0}"
Python: sorting items in a dictionary by a part of a key?,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))"
How to write individual bits to a text file in python?,"open('file.bla', 'wb')"
customizing just one side of tick marks in matplotlib using spines,"ax.tick_params(axis='y', direction='out')"
Grouping dataframes in pandas?,"df.groupby(['A', 'B'])['C'].unique()"
split items in list,"result = [item for word in words for item in word.split(',')]"
Replace console output in Python,sys.stdout.flush()
Storing a matlab file using python,"scipy.io.savemat('test.mat', data)"
how to create a group ID based on 5 minutes interval in pandas timeseries?,df.groupby(pd.TimeGrouper('5Min'))['val'].mean()
Plotting terrain as background using matplotlib,plt.show()
How to create range of numbers in Python like in MATLAB,"print(np.linspace(1, 3, num=5))"
How to create nested list from flatten list?,"[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]"
How to iterate over a range of keys in a dictionary?,"d = OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])"
change figure size and figure format in matplotlib,"plt.figure(figsize=(3, 4))"
What is the definition of mean in pandas data frame?,df['col'] = df['col'].map(int)
Delete letters from string,""""""""""""".join(filter(str.isdigit, '12454v'))"
swap values in a tuple/list inside a list in python?,"[(t[1], t[0]) for t in mylist]"
"Regex, find first - Python","re.findall('<wx\\.[^<]*<[^<]*> >', i)"
Python Save to file,file.close()
How to run a python script from IDLE interactive shell?,"exec(compile(open('helloworld.py').read(), 'helloworld.py', 'exec'))"
Python Pandas Dataframe GroupBy Size based on condition,"df.groupby(['id', 'date1']).apply(lambda x: (x['date1'] == x['date2']).sum())"
how to initialize multiple columns to existing pandas DataFrame,df.reindex(columns=list['cd'])
How to convert pandas dataframe so that index is the unique set of values and data is the count of each value?,df['Qu1'].value_counts()
Generating an MD5 checksum of a file,"print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())"
Create multiple columns in Pandas Dataframe from one function,"df[['IV', 'Vega']] = df.apply(newtonRap, axis=1)"
How to delete a character from a string using python?,"s = s.replace('M', '')"
How to add a column to a multi-indexed DataFrame?,"df.insert(1, ('level1', 'age'), pd.Series([13]))"
"python, format string","""""""{0} %s {1}"""""".format('foo', 'bar')"
How to call a system command with specified time limit in Python?,self.process.terminate()
Using variables in Python regular expression,re.compile('{}-\\d*'.format(user))
Using Colormaps to set color of line in matplotlib,plt.show()
Creating a dictionary from a CSV file,"{'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']}"
Assign a number to each unique value in a list,"[1, 1, 3, 3, 3, 2, 2, 1, 2, 0, 0, 0, 1]"
Python: Logging TypeError: not all arguments converted during string formatting,logging.info('date={}'.format(date))
Pandas DataFrame to List of Dictionaries,df.to_dict('records')
Sorting a list of lists of dictionaries in python,key = lambda x: sum(y['play'] for y in x)
How to find row of 2d array in 3d numpy array,"np.all(np.all(test, axis=2), axis=1)"
Slicing numpy array with another array,"numpy.ma.array(strided, mask=mask)"
Ordering a list of dictionaries in python,"mylist.sort(key=operator.itemgetter('weight', 'factor'))"
Convert unicode codepoint to UTF8 hex in python,"chr(int('fd9b', 16)).encode('utf-8')"
MultiValueDictKeyError in Django,"request.GET.get('username', '')"
Changing the text on a label,self.depositLabel.config(text='change the value')
How to modify the elements in a list within list,"L = [[1, 2, 3], [4, 5, 6], [3, 4, 6]]"
Python: How do I format a date in Jinja2?,{{car.date_of_manufacture.strftime('%Y-%m-%d')}}
How can I use Bootstrap with Django?,STATIC_URL = '/static/'
Python/Matplotlib - Is there a way to make a discontinuous axis?,"ax.plot(x, y, 'bo')"
Python - converting a string of numbers into a list of int,"map(int, example_string.split(','))"
Replace keys in a dictionary,"keys = {'a': 'append', 'h': 'horse', 'e': 'exp', 's': 'see'}"
Django filter JSONField list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
How do I rename columns in a python pandas dataframe?,"country_data_table.rename(columns={'value': country.name}, inplace=True)"
How can I start a Python thread FROM C++?,system('python myscript.py')
How to accumulate an array by index in numpy?,"np.add.at(a, np.array([1, 2, 2, 1, 3]), np.array([1, 1, 1, 1, 1]))"
How can I fill a matplotlib grid?,plt.show()
Counting the amount of occurences in a list of tuples,"Counter({'12392': 2, '7862': 1})"
Python remove anything that is not a letter or number,"re.sub('[\\W_]+', '', s)"
Pandas: Subtract row mean from each element in row,df.mean(axis=1)
How to sort a Pandas DataFrame according to multiple criteria?,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
How to find the index of a value in 2d array in Python?,zip(*np.where(a == 1))
How to I load a tsv file into a Pandas DataFrame?,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')"
How to decode a 'url-encoded' string in python,urllib.parse.unquote(urllib.parse.unquote('FireShot3%2B%25282%2529.png'))
Efficient way to convert a list to dictionary,"{k: v for k, v in (e.split(':') for e in lis)}"
Find max overlap in list of lists,"[[0, 1, 5], [2, 3], [13, 14], [4], [6, 7], [8, 9, 10, 11], [12], [15]]"
How to generate random numbers that are different?,"random.sample(range(1, 50), 6)"
finding out absolute path to a file from python,os.path.abspath(__file__)
How can I show figures separately in matplotlib?,plt.show()
How do I remove identical items from a list and sort it in Python?,"['a', 'b', 'c', 'd', 'e', 'f']"
How to input 2 integers in one line in Python?,"a, b = map(int, input().split())"
"Python mySQL Update, Working but not updating table",dbb.commit()
Python insert numpy array into sqlite3 database,"cur.execute('insert into test (arr) values (?)', (x,))"
Exit while loop in Python,sys.exit()
How to remove the space between subplots in matplotlib.pyplot?,"fig.subplots_adjust(wspace=0, hspace=0)"
Updating csv with data from a csv with different formatting,"cdf1.to_csv('temp.csv', index=False)"
Executing a C program in python?,"call(['./spa', 'args', 'to', 'spa'])"
How to dynamically assign values to class properties in Python?,"setattr(self, attr, group)"
Equivalent of j in Numpy,np.array([1j])
Python Pandas: How to get the row names from index of a dataframe?,df.index
How do I model a many-to-many relationship over 3 tables in SQLAlchemy (ORM)?,session.query(Shots).filter_by(event_id=event_id).count()
Replacing instances of a character in a string,"line = line.replace(';', ':')"
How can I iterate and apply a function over a single level of a DataFrame with MultiIndex?,"df.groupby(level=0, axis=1).sub(df['IWWGCW'].values)"
Python Requests Multipart HTTP POST,"requests.post(url, headers=headers, files=files, data=data)"
How to authenticate a public key with certificate authority using Python?,"requests.get(url, verify=True)"
sum a list of numbers in Python,sum(list_of_nums)
how to parse a list or string into chunks of fixed length,"split_list = [the_list[i:i + n] for i in range(0, len(the_list), n)]"
Code for line of best fit of a scatter plot in python,"plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))"
SQLAlchemy: a better way for update with declarative?,session.query(User).filter_by(id=123).update({'name': 'Bob Marley'})
Pandas DataFrame performance,df.loc['2000-1-1':'2000-3-31']
How to authenticate a public key with certificate authority using Python?,"requests.get(url, verify='/path/to/cert.pem')"