intent
stringlengths
4
183
snippet
stringlengths
2
1k
reshape pandas dataframe from rows to columns
df2.groupby('Name').apply(tgrp)
how do i convert a string of hexadecimal values to a list of integers?
struct.unpack('11B', s)
reading gps rinex data with pandas
df.set_index(['%_GPST', 'satID'])
search for "does-not-contain" on a dataframe in pandas
~df['col'].str.contains(word)
pythonic way to convert list of dicts into list of namedtuples
items = [some(m['a'].split(), m['d'], m['n']) for m in dl]
remove tags from a string `mystring`
re.sub('<[^>]*>', '', mystring)
how do i can format exception stacktraces in python logging?
logging.info('Sample message')
how do i create a list of unique random numbers?
random.sample(list(range(100)), 10)
delete digits at the end of string `s`
re.sub('\\b\\d+\\b', '', s)
in python, how do i index a list with another list?
T = [L[i] for i in Idx]
get values from a dictionary `my_dict` whose key contains the string `date`
[v for k, v in list(my_dict.items()) if 'Date' in k]
using flask blueprints, how to fix url_for from breaking if a subdomain is specified?
app.config['SERVER_NAME'] = 'example.net'
python append to array in json object
jsobj['a']['b']['e'].append(dict(f=var3))
find the euclidean distance between two 3-d arrays `a` and `b`
np.sqrt(((A - B) ** 2).sum(-1))
python: confusions with urljoin
urljoin('http://some', 'thing')
understanding == applied to a numpy array
np.arange(3)
capitalizing non-ascii words in python
print('\xe9'.capitalize())
sorting a defaultdict `d` by value
sorted(list(d.items()), key=lambda k_v: k_v[1])
how to compare dates in django
return date.today() > self.date
execute shell script from python with variable
subprocess.call(['test.sh', str(domid)])
convert a date string `s` to a datetime object
datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
how do i create a web interface to a simple python script?
app.run()
stacked bar chart with differently ordered colors using matplotlib
plt.show()
matplotlib boxplot without outliers
boxplot([1, 2, 3, 4, 5, 10], showfliers=False)
generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`
print(list(itertools.product([1, 2, 3], [4, 5, 6])))
python dictionary to url parameters
urllib.parse.urlencode({'p': [1, 2, 3]}, doseq=True)
how to group dataframe by a period of time?
df.groupby([df['Source'], pd.TimeGrouper(freq='Min')])
get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`
{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}
selecting elements of a python dictionary greater than a certain value
{k: v for k, v in list(dict.items()) if v > something}
how to write a multidimensional array to a text file?
np.savetxt('test.txt', x)
remove strings from a list that contains numbers in python
my_list = [item for item in my_list if item.isalpha()]
for loop in python
list(range(0, 30, 5))
extract all keys from a list of dictionaries
[list(d.keys()) for d in LoD]
how to slice a 2d python array? fails with: "typeerror: list indices must be integers, not tuple"
array([[1, 3], [4, 6], [7, 9]])
python: convert list of key-value tuples into dictionary?
dict([('A', 1), ('B', 2), ('C', 3)])
matplotlib large set of colors for plots
plt.show()
check if a user `user` is in a group from list of groups `['group1', 'group2']`
return user.groups.filter(name__in=['group1', 'group2']).exists()
how do i merge a 2d array in python into one string with list comprehension?
[item for innerlist in outerlist for item in innerlist]
python regex alternative for join
re.sub('(.)(?=.)', '\\1-', s)
filtering out strings that contain 'ab' from a list of strings `lst`
[k for k in lst if 'ab' in k]
how to draw "two directions widths line" in matplotlib
plt.show()
writing hex data into a file
f.write(hex(i))
how to terminate process from python using pid?
process.terminate()
writing a list of sentences to a single column in csv with python
writer.writerows(['Hi, there'])
dictionary keys match on list; get key/value pair
new_dict = {k: my_dict[k] for k in my_list if k in my_dict}
string regex two mismatches python
re.findall('(?=([A-Z]SQP|S[A-Z]QP|SS[A-Z]P|SSQ[A-Z]))', s)
find max in nested dictionary
max(d, key=lambda x: d[x]['count'])
how to update matplotlib's imshow() window interactively?
draw()
break string into list elements based on keywords
['Na', '1', 'H', '1', 'C', '2', 'H', '3', 'O', '2']
select dataframe rows between two dates
df['date'] = pd.to_datetime(df['date'])
escaping quotes in string
replace('"', '\\"')
create dynamic button in pyqt
button.clicked.connect(self.commander(command))
pandas: counting unique values in a dataframe
pd.value_counts(d[['col_title1', 'col_title2']].values.ravel())
efficient way to convert a list to dictionary
{k: v for k, v in (e.split(':') for e in lis)}
how to plot empirical cdf in matplotlib in python?
plt.show()
gnuplot linecolor variable in matplotlib?
plt.show()
how to run spark java code in airflow?
sys.path.append(os.path.join(os.environ['SPARK_HOME'], 'bin'))
parsing json fields in python
print(b['indices']['client_ind_2']['index'])
how do i connect to a mysql database in python?
cur.execute('SELECT * FROM YOUR_TABLE_NAME')
remove characters "!@#$" from a string `line`
line.translate(None, '!@#$')
listing files from a directory using glob python
glob.glob('[!hello]*.txt')
find the index of the element with the maximum value from a list 'a'.
max(enumerate(a), key=lambda x: x[1])[0]
upload files to google cloud storage from appengine app
upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')
how can i list only the folders in zip archive in python?
[x for x in file.namelist() if x.endswith('/')]
how do you set up a flask application with sqlalchemy for testing?
app.run()
match regex 'abc(de)fg(123)' on string 'abcdefg123 and again abcdefg123'
re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')
python + mysqldb executemany
cursor.close()
creating a list by iterating over a dictionary
['{}_{}'.format(k, v) for k, l in list(d.items()) for v in l]
remove newline in string `s` on the right side
s.rstrip()
how can i insert a new tag into a beautifulsoup object?
self.new_soup.body.insert(3, new_tag)
how can i vectorize the averaging of 2x2 sub-arrays of numpy array?
y.mean(axis=(1, 3))
get only certain fields of related object in django
Comment.objects.filter(user=user).values_list('user__name', 'user__email')
most efficient method to get key for similar values in a dict
trie = {'a': {'b': {'e': {}, 's': {}}, 'c': {'t': {}, 'k': {}}}}
how to make a python script which can logoff, shutdown, and restart a computer?
subprocess.call(['shutdown', '/r'])
how to do simple http redirect using python?
print('Location:URL\r\n')
python date string formatting
my_date.strftime('%-m/%-d/%y')
how to hide output of subprocess in python 2.7
retcode = os.system("echo 'foo' &> /dev/null")
how to check whether a method exists in python?
hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
convert double to float in python
struct.unpack('f', struct.pack('f', 0.00582811585976))
efficient way to convert a list to dictionary
dict([x.split(':') for x in a])
how to remove gaps between subplots in matplotlib?
plt.show()
delete an element `key` from a dictionary `d`
del d[key]
reading a triangle of numbers into a 2d array of ints in python
arr = [[int(i) for i in line.split()] for line in open('input.txt')]
extract data field 'bar' from json object
json.loads('{"foo": 42, "bar": "baz"}')['bar']
pandas create new column based on values from other columns
df.apply(lambda row: label_race(row), axis=1)
editing the date formatting of x-axis tick labels in matplotlib
ax.xaxis.set_major_formatter(myFmt)
create a list of integers with duplicate values in python
print([u for v in [[i, i] for i in range(5)] for u in v])
select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`
soup.select('div[id^="value_xxx_c_1_f_8_a_"]')
how do i sort a list of strings in python?
mylist.sort(key=str.lower)
reverse a string `a` by 2 characters at a time
"""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))
slice `url` with '&' as delimiter to get "http://www.domainname.com/page?content_item_id=1234" from url "http://www.domainname.com/page?content_item_id=1234&param2&param3 "
url.split('&')
count occurrence of a character in a string
"""Mary had a little lamb""".count('a')
how do i display add model in tabular format in the django admin?
{'fields': ('first_name', 'last_name', 'address', 'city', 'state')}
how to sort with lambda in python
a = sorted(a, key=lambda x: x.modified, reverse=True)
get key-value pairs in dictionary `my_dictionary` for all keys in list `my_list` in the order they appear in `my_list`
dict(zip(my_list, map(my_dictionary.get, my_list)))
is it possible to take an ordered "slice" of a dictionary in python based on a list of keys?
map(my_dictionary.get, my_list)
best way to strip punctuation from a string in python
s.translate(None, string.punctuation)
how to parse dates with -0400 timezone string in python?
datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')
sum a list of numbers in python
sum(Decimal(i) for i in a)
pandas for duplicating one line to fill dataframe
newsampledata.reindex(newsampledata.index.repeat(n)).reset_index(drop=True)