intent
stringlengths
4
183
snippet
stringlengths
2
1k
how to change user-agent on google app engine urlfetch service?
urlfetch.fetch(url, headers={'User-Agent': 'MyApplication_User-Agent'})
how to render a doctype with python's xml.dom.minidom?
print(doc.toxml())
pandas joining multiple dataframes on columns
df1.merge(df2, on='name').merge(df3, on='name')
is there a matplotlib counterpart of matlab "stem3"?
plt.show()
compare python pandas dataframes for matching rows
pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner')
symlinks on windows?
kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)
can i use a class attribute as a default value for an instance method?
my_instance = MyClass(name='new name')
removing items from a nested list python
[[j for j in families[i] if i != j] for i in range(len(families))]
reading array from config file in python
config.get('common', 'folder').split('\n')
python pandas -- merging mostly duplicated rows
grouped = data.groupby(['date', 'name'])
python sorting list of dictionaries by multiple keys
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))
sorting a list of tuples with multiple conditions
sorted_by_length = sorted(list_, key=lambda x: (x[0], len(x[1]), float(x[1])))
split a string into 2 in python
firstpart, secondpart = string[:len(string) / 2], string[len(string) / 2:]
replace parentheses and all data within it with empty string '' in column 'name' of dataframe `df`
df['name'].str.replace('\\(.*\\)', '')
using pandas, how do i subsample a large dataframe by group in an efficient manner?
subsampled = df.ix[(choice(x) for x in list(grouped.groups.values()))]
cross product of a vector in numpy
np.cross(a, b, axis=0)
applying borders to a cell in openpyxl
wb.save('border_test.xlsx')
most efficient way in python to iterate over a large file (10gb+)
collections.Counter(map(uuid, open('log.txt')))
order a list of lists `l1` by the first value
l1.sort(key=lambda x: int(x[0]))
how to produce an exponentially scaled axis?
plt.show()
how do i get the raw representation of a string in python?
print(rawstr(test7))
how to get the indices list of all nan value in numpy array?
array([[1, 2], [2, 0]])
merge two lists `a` and `b` into a single list
[j for i in zip(a, b) for j in i]
summarizing dataframe into a dictionary
df.groupby('date')['level'].first().apply(np.ceil).astype(int).to_dict()
plotting a 2d array with matplotlib
plt.show()
sort list of strings `the_list` by integer suffix before "_"
sorted(the_list, key=lambda x: int(x.split('_')[1]))
how do i get rid of python tkinter root window?
root.destroy()
make new column 'c' in panda dataframe by adding values from other columns 'a' and 'b'
df['C'] = df['A'] + df['B']
how do i sort a python list of time values?
sorted(['14:10:01', '03:12:08'])
splitting dictionary/list inside a pandas column into separate columns
pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
how to plot a gradient color line in matplotlib?
plt.show()
sorting python list based on the length of the string
xs.sort(lambda x, y: cmp(len(x), len(y)))
how to get the concrete class name as a string?
instance.__class__.__name__
regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
re.sub('l+', 'l', 'lollll')
is there a way to copy only the structure (not the data) of a pandas dataframe?
df2 = pd.DataFrame(data=None, columns=df1.columns, index=df1.index)
pythonic way to filter list for elements with unique length
list({len(s): s for s in jones}.values())
convert numbers to grades in python list
li = map(lambda x: '{0} - {1}'.format(x, grade(x)), s)
matplotlib: is a changing background color possible?
plt.axvspan(x, x2, facecolor='g', alpha=0.5)
python: create list of tuples from lists
z = zip(x, y)
dynamic module import in python
my_module = importlib.import_module('os.path')
building up an array in numpy/scipy by iteration in python?
array([0, 1, 4, 9, 16])
check if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`
all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])
convert list of tuples to multiple lists in python
map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
list all ".txt" files of a directory "/home/adam/"
print(glob.glob('/home/adam/*.txt'))
5 maximum values in a python dictionary
max(A, key=A.get)
splitting a string into a list (but not separating adjacent numbers) in python
[el for el in re.split('(\\d+)', string) if el.strip()]
change current working directory in python
os.chdir('chapter3')
how to send multiple input field values with same name?
relations = request.POST.getlist('relations')
get value of first child of xml node `name`
name[0].firstChild.nodeValue
in python, how to join a list of tuples into one list?
b = [i for sub in a for i in sub]
how to create a hyperlink with a label in tkinter?
webbrowser.open_new('file://c:\\test\\test.csv')
how to rewrite output in terminal
sys.stdout.flush()
python: split string with multiple delimiters
re.split('; |, ', str)
remove a substring ".com" from the end of string `url`
url = re.sub('\\.com$', '', url)
how to smooth matplotlib contour plot?
plt.show()
index the first and the last n elements of a list
l[:3] + l[-3:]
changing time frequency in pandas dataframe
new = df.resample('T', how='mean')
change the background colour of the button `pushbutton` to red
self.pushButton.setStyleSheet('background-color: red')
what's a quick one-liner to remove empty lines from a python string?
text = os.linesep.join([s for s in text.splitlines() if s])
how to get the name of an open file?
print(os.path.basename(sys.argv[0]))
equivalent of j in numpy
np.array([1j])
truncate `\r\n` from each string in a list of string `example`
example = [x.replace('\r\n', '') for x in example]
how to check if string has the same characters in python
len(set('aaaa')) == 1
how to convert from infix to postfix/prefix using ast python module?
['x', 'cos']
how to calculate next friday in python?
d += datetime.timedelta(1)
a list > a list of lists
[['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
list comprehension that produces integers between 11 and 19
[i for i in range(100) if i > 10 if i < 20]
how to add a new row to an empty numpy array
arr = np.append(arr, np.array([[4, 5, 6]]), axis=0)
php's strtr for python
print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
plotting arrows with different color in matplotlib
plt.show()
get rows that have the same value across its columns in pandas
df.apply(pd.Series.nunique, axis=1)
adding values from tuples of same length
coord = tuple(sum(x) for x in zip(coord, change))
how to check if a column exists in pandas
df['sum'] = df['A'] + df['C']
using a conditional in the python interpreter -c command
python - mplatform
python print array with new line
print('\n'.join(op))
how to avoid python/pandas creating an index in a saved csv?
pd.to_csv('your.csv', index=False)
how to remove multiple columns that end with same text in pandas?
df.select(lambda x: re.search('prefix$', str(x)) is None, axis=1)
running python code contained in a string
eval("print('Hello')")
mutli-threading python with tkinter
root.mainloop()
what pandas data type is passed to transform or apply in a groupby
df.groupby(['category'])[['data_1', 'data_2']].transform(f)
calling an external command "ls -l"
call(['ls', '-l'])
divide the values of two dictionaries in python
{k: (float(d2[k]) / d1[k]) for k in d2}
read from a gzip file in python
f.close()
check if all values of iterable are zero
list(l) == [0] * len(l)
how can i do multiple substitutions using regex in python?
re.sub('([characters])', '\\1\\1', text.read())
check if "blah" is in string `somestring`
if ('blah' not in somestring): pass
3d plot with matplotlib
ax.plot_surface(x, y, z, rstride=10, cstride=10, alpha=0.3)
replace repeated instances of "*" with a single instance of "*"
re.sub('\\*+', '*', text)
how to convert a list of multiple integers into a single integer?
x = [1, 3, 5]
how to create a menu and submenus in python curses?
curses.doupdate()
reverse string 'foo'
''.join(reversed('foo'))
how to merge two dataframe in pandas to replace nan
a.where(~np.isnan(a), other=b, inplace=True)
generate md5 checksum of file in the path `full_path` in hashlib
print(hashlib.md5(open(full_path, 'rb').read()).hexdigest())
how do i add space between two variables after a print in python
print(str(count) + ' ' + str(conv))
how to convert a hex string to hex number
print(hex(new_int)[2:])
stop infinite page load in selenium webdriver - python
driver.send_keys(Keys.CONTROL + 'Escape')
python json encoding
json.dumps({'apple': 'cat', 'banana': 'dog', 'pear': 'fish'})
python: display special characters when using print statement
print(repr(a).replace(' ', '\\s'))
extract values not equal to 0 from numpy array `a`
a[a != 0]
capturing emoticons using regular expression in python
re.match('[:;][)(](?![)(])', str)