intent
stringlengths
4
183
snippet
stringlengths
2
1k
convert binary string '11111111' to integer
int('11111111', 2)
fixing color in scatter plots in matplotlib
plt.show()
python pandas dataframe slicing by date conditions
df.sort_index()
python pandas - how to flatten a hierarchical index in columns
df.columns = df.columns.get_level_values(0)
expanding numpy array over extra dimension
np.tile(b, (2, 2, 2))
python pandas: replace values multiple columns matching multiple columns from another dataframe
df2.rename(columns={'OCHR': 'chr', 'OSTOP': 'pos'}, inplace=True)
finding the index of elements based on a condition using python list comprehension
a[:] = [x for x in a if x <= 2]
converting string to tuple
print([(x[0], x[-1]) for x in l])
smartest way to join two lists into a formatted string
c = ', '.join('%s=%s' % t for t in zip(a, b))
dynamically updating plot in matplotlib
plt.draw()
replace rarely occurring values in a pandas dataframe
g = df.groupby('column_name')
numpy `logical_or` for more than two arguments
np.logical_or.reduce((x, y, z))
python: sort an array of dictionaries with custom comparator?
key = lambda d: (not 'rank' in d, d['rank'])
wait for shell command `p` evoked by subprocess.popen to complete
p.wait()
get the sum of the products of each pair of corresponding elements in lists `a` and `b`
sum(x * y for x, y in zip(a, b))
how to replace values with none in pandas data frame in python?
df.replace('-', np.nan)
how to join components of a path when you are constructing a url in python
urlparse.urljoin('/media/', 'js/foo.js')
python - how to format variable number of arguments into a string?
function_in_library('Hello %s' % ', '.join(['%s'] * len(my_args)), my_args)
iterate through words of a file in python
words = open('myfile').read().split()
get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log'
os.path.commonprefix(['/usr/var', '/usr/var2/log'])
elegant way to create a dictionary of pairs, from a list of tuples?
dict(x[1:] for x in reversed(myListOfTuples))
remove all the elements that occur in one list from another
l3 = [x for x in l1 if x not in l2]
create new columns in pandas from python nested lists
df.A.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)
how to sort list of lists according to length of sublists
sorted(a, key=len)
print current date and time in a regular format
time.strftime('%Y-%m-%d %H:%M')
regex to separate numeric from alpha
re.findall('(\\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')
confusing with the usage of regex in python
re.findall('[a-z]*', '123456789')
python int to binary?
bin(10)
python getting a list of value from list of dict
[d['value'] for d in l]
filter objects month wise in django model `sample` for year `2011`
Sample.objects.filter(date__year='2011', date__month='01')
how to flatten a pandas dataframe with some columns as json?
df[['id', 'name']].join([A, B])
sort list of tuples by reordering tuples
sorted(A, key=operator.itemgetter(2, 0, 1))
encode `u'x\xc3\xbcy\xc3\x9f'` as unicode and decode with utf-8
'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
how to create a ratings csr_matrix in scipy?
scipy.sparse.csr_matrix([column['rating'], column['user'], column['movie']])
find dictionary items whose key matches a substring
[value for key, value in list(programs.items()) if 'new york' in key.lower()]
how to iterate through a list of tuples containing three pair values?
[(1, 'B', 'A'), (2, 'C', 'B'), (3, 'C', 'A')]
printing numbers rounding up to third decimal place
print('%.3f' % 3.1415)
how to do pearson correlation of selected columns of a pandas data frame
df.corr().iloc[:-1, (-1)]
matplotlib artist to stay same size when zoomed in but also move with panning?
plt.show()
convert a string of numbers `example_string` separated by `,` into a list of integers
map(int, example_string.split(','))
how to create a dictionary using two lists in python?
dict(zip(x, y))
append to file 'test1' content 'koko'
with open('test1', 'ab') as f: pass
running python code contained in a string
print('hello')
remove newline in string `s` on the left side
s.lstrip()
most pythonic way to convert a list of tuples
zip(*list_of_tuples)
extracting only characters from a string in python
""" """.join(re.split('[^a-zA-Z]*', 'your string'))
how to use the mv command in python with subprocess
subprocess.call(['mv', '/home/somedir/subdir/*', 'somedir/'])
split string 'fooxyzbar' based on case-insensitive matching using string 'xyz'
re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')
remove duplicates from a list of sets 'l'
[set(item) for item in set(frozenset(item) for item in L)]
selecting data between specific hours in a pandas dataframe
df_new = df[(df['time'] > start_time) & (df['time'] < end_time)]
regex to get list of all words with specific letters (unicode graphemes)
print(' '.join(get_words(['k', 'c', 't', 'a'])))
idiom for flattening a shallow nested list: how does it work?
[x for y in l for x in y]
python regex to match non-ascii names
regexRef = re.compile('\\w', re.UNICODE)
match zero-or-more instances of lower case alphabet characters in a string `f233op `
re.findall('([a-z]*)', 'f233op')
numpy: check if array 'a' contains all the numbers in array 'b'.
numpy.array([(x in a) for x in b])
using headers with the python requests library's get method
r = requests.get('http://www.example.com/', headers={'content-type': 'text'})
python: getting rid of \u200b from a string using regular expressions
'used\u200b'.replace('\u200b', '*')
regular expression to return all characters between two special characters
match.group(1)
flask confusion with app
app = Flask(__name__)
python: test if value can be converted to an int in a list comprehension
[row for row in listOfLists if row[x].isdigit()]
how can i backup and restore mongodb by using pymongo?
db.col.find({'price': {'$lt': 100}})
how to create a list with the characters of a string?
['5', '+', '6']
how to continue a task when fabric receives an error
sudo('rm tmp')
save a subplot in matplotlib
fig.savefig('full_figure.png')
json query that returns parent element and child data?
dict((k, v['_status']['md5']) for k, v in list(json_result.items()))
get list item by attribute in python
items = [item for item in container if item.attribute == value]
find a specific tag with beautifulsoup
soup.findAll('div', style='width=300px;')
how to set the unit length of axis in matplotlib?
plt.show()
sort list of mixed strings based on digits
sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))
check the status code of url "http://www.stackoverflow.com"
urllib.request.urlopen('http://www.stackoverflow.com').getcode()
is there a python equivalent to ruby's string interpolation?
"""my {0} string: {1}""".format('cool', 'Hello there!')
unpack first and second bytes of byte string `ps` into integer
struct.unpack('h', pS[0:2])
extract the 2nd elements from a list of tuples
[x[1] for x in elements]
convert a list with string `['1', '2', '3']` into list with integers
map(int, ['1', '2', '3'])
intersection of 2d and 1d numpy array
A[:, 3:].flat[np.in1d(A[:, 3:], B)] = 0
generate 6 random numbers between 1 and 50
random.sample(range(1, 50), 6)
python - how to format variable number of arguments into a string?
'Hello %s' % ', '.join(map(str, my_args))
get keys with same value in dictionary `d`
print([key for key in d if d[key] == 1])
code to detect all words that start with a capital letter in a string
print([word for word in words if word[0].isupper()])
passing the '+' character in a post request in python
f = urllib.request.urlopen(url, urllib.parse.unquote(urllib.parse.urlencode(params)))
find numpy array rows which contain any of list
np.in1d(a, b).reshape(a.shape).any(axis=1)
confusing with the usage of regex in python
re.findall('([a-z])*', 'f233op')
create list of dictionary python
[{'data': 2}, {'data': 2}, {'data': 2}]
merge column 'word' in dataframe `df2` with column 'word' on dataframe `df1`
df1.merge(df2, how='left', on='word')
substract 1 hour and 10 minutes from current time
t = datetime.datetime.now() (t - datetime.timedelta(hours=1, minutes=10))
make tkinter widget take focus
root.mainloop()
how to get the current model instance from inlineadmin in django
return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
getting the docstring from a function
help(my_func)
post json to python cgi
print(json.dumps(result))
read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`
df = pd.read_csv('comma.csv', quotechar="'")
how to draw line inside a scatter plot
ax.set_ylabel('TPR or sensitivity')
passing variable from javascript to server (django)
document.getElementById('geolocation').submit()
regenerate vector of randoms in python
np.random.normal(0, 1, (100, 3))
how can i slice each element of a numpy array of strings?
a.view('U1').reshape(4, -1)[:, 1:3]
join elements of each tuple in list `a` into one string
[''.join(x) for x in a]
splitting numpy array based on value
zeros = np.where(a == 0)[0]
how to duplicate rows in pandas, based on items in a list
df['data'] = df['data'].apply(clean_string_to_list)
clear tkinter canvas `canvas`
canvas.delete('all')
python load zip with modules from memory
zipfile.ZipFile(zipbytes)
what is the most efficient way to remove a group of indices from a list of numbers in python 2.7?
return [numbers[i] for i in range(len(numbers)) if i not in indices]