prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
|---|---|
get value at index `[2, 0]` in dataframe `df`
|
df.iloc[2, 0]
|
hange the font size on plot `matplotlib` to 22
|
matplotlib.rcParams.update({'font.size': 22})
|
verting dictionary `d` into a dataframe `pd` with keys as data for column 'Date' and the corresponding values as data for column 'DateValue'
|
pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])
|
eate a dataframe containing the multiplication of elementwise in dataframe `df` and dataframe `df2` using index name and column labels of dataframe `df`
|
pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)
|
extract floating number from string 'Current Level: 13.4 db.'
|
re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')
|
extract floating point numbers from a string 'Current Level: 13.2 db or 14.2 or 3'
|
re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')
|
pair each element in list `it` 3 times into a tuple
|
zip(it, it, it)
|
lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`
|
df['x'].str.lower()
|
ppend dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`
|
jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})
|
Concat a list of strings `lst` using string formatting
|
"""""".join(lst)
|
m values greater than 0 in dictionary `d`
|
sum(v for v in list(d.values()) if v > 0)
|
flask application `app` in debug mode.
|
app.run(debug=True)
|
drop rows whose index value in list `[1, 3]` in dataframe `df`
|
df.drop(df.index[[1, 3]], inplace=True)
|
eplace nan values in a pandas data frame with the average of colum
|
df.apply(lambda x: x.fillna(x.mean()), axis=0)
|
extract attribute `my_attr` from each object in list `my_list`
|
[o.my_attr for o in my_list]
|
python get time stamp on file `file` in '%m/%d/%Y' form
|
time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
|
heck if dictionary `subset` is a subset of dictionary `superset`
|
all(item in list(superset.items()) for item in list(subset.items()))
|
Convert integer elements in list `wordids` to string
|
[str(wi) for wi in wordids]
|
Reset the indexes of a pandas data frame
|
df2 = df.reset_index()
|
format datetime in `dt` as string in format `'%m/%d/%Y`
|
dt.strftime('%m/%d/%Y')
|
format floating point number `TotalAmount` to be rounded off to two decimal places and have a comma thousands' seperator
|
print('Total cost is: ${:,.2f}'.format(TotalAmount))
|
m the values in each row of every two adjacent columns in dataframe `df`
|
df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')
|
eate list `randomList` with 10 random floating point numbers between 0.0 and 1.0
|
randomList = [random.random() for _ in range(10)]
|
find href value that has string 'follow?page' inside
|
print(soup.find('a', href=re.compile('.*follow\\?page.*')))
|
mmediately see output of print statement that doesn't end in a newline
|
sys.stdout.flush()
|
get a random key `country` and value `capital` form a dictionary `d`
|
country, capital = random.choice(list(d.items()))
|
plit string `Word to Split` into a list of character
|
list('Word to Split')
|
Create a list containing words that contain vowel letter followed by the same vowel in file 'file.text'
|
[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]
|
Validate IP address using Regex
|
pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')
|
execute file 'filename.py'
|
exec(compile(open('filename.py').read(), 'filename.py', 'exec'))
|
SQLAlchemy count the number of rows with distinct values in column `name` of table `Tag`
|
session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
|
emove null columns in a dataframe `df`
|
df = df.dropna(axis=1, how='all')
|
heck if all lists in list `L` have three elements of integer 1
|
all(x.count(1) == 3 for x in L)
|
Get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`
|
[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]
|
lear the textbox `text` in tkinter
|
tex.delete('1.0', END)
|
Convert long int `myNumber` into date and time represented in the the string format '%Y%m%d %H:%M:%S'
|
datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
|
Spawn a process to run python script `myscript.py` in C++
|
system('python myscript.py')
|
a list `your_list` of class objects by their values for the attribute `anniversary_score`
|
your_list.sort(key=operator.attrgetter('anniversary_score'))
|
list `your_list` by the `anniversary_score` attribute of each objec
|
your_list.sort(key=lambda x: x.anniversary_score)
|
vert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow
|
print(type(tf.Session().run(tf.constant([1, 2, 3]))))
|
vert list `a` from being consecutive sequences of tuples into a single sequence of eleme
|
list(itertools.chain(*a))
|
Set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`
|
count.setdefault('a', 0)
|
Do group by on `cluster` column in `df` and get its me
|
df.groupby(['cluster']).mean()
|
get number in list `myList` closest in value to number `myNumber`
|
min(myList, key=lambda x: abs(x - myNumber))
|
heck if any of the items in `search` appear in `string`
|
any(x in string for x in search)
|
earch for occurrences of regex pattern `pattern` in string `url`
|
print(pattern.search(url).group(1))
|
factorize all string values in dataframe `s` into flo
|
(s.factorize()[0] + 1).astype('float')
|
Get a list `C` by subtracting values in one list `B` from corresponding values in another list `A`
|
C = [(a - b) for a, b in zip(A, B)]
|
derive the week start for the given week number and year ‘2011, 4, 0’
|
datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')
|
vert a list of strings `['1', '1', '1']` to a list of number
|
map(int, ['1', '-1', '1'])
|
eate datetime object from 16sep2012
|
datetime.datetime.strptime('16Sep2012', '%d%b%Y')
|
pdate fields in Django model `Book` with arguments in dictionary `d` where primary key is equal to `pk`
|
Book.objects.filter(pk=pk).update(**d)
|
pdate the fields in django model `Book` using dictionary `d`
|
Book.objects.create(**d)
|
print a digit `your_number` with exactly 2 digits after decimal
|
print('{0:.2f}'.format(your_number))
|
generate a 12digit random number
|
random.randint(100000000000, 999999999999)
|
generate a random 12digit number
|
int(''.join(str(random.randint(0, 9)) for _ in range(12)))
|
generate a random 12digit number
|
"""""".join(str(random.randint(0, 9)) for _ in range(12))
|
generate a 12digit random number
|
'%0.12d' % random.randint(0, 999999999999)
|
emove specific elements in a numpy array `a`
|
numpy.delete(a, index)
|
list `trial_list` based on values of dictionary `trail_dict`
|
sorted(trial_list, key=lambda x: trial_dict[x])
|
ead a single character from std
|
sys.stdin.read(1)
|
get a list of characters in string `x` matching regex pattern `pattern`
|
print(re.findall(pattern, x))
|
get the context of a search by keyword 'My keywords' in beautifulsoup `soup`
|
k = soup.find(text=re.compile('My keywords')).parent.text
|
vert rows in pandas data frame `df` into l
|
df.apply(lambda x: x.tolist(), axis=1)
|
vert a 1d `A` array to a 2d array `B`
|
B = np.reshape(A, (-1, 2))
|
app `app` on host '192.168.0.58' and port 9000 in Flask
|
app.run(host='192.168.0.58', port=9000, debug=False)
|
encode unicode string '\xc5\xc4\xd6' to utf8 code
|
print('\xc5\xc4\xd6'.encode('UTF8'))
|
get the first element of each tuple from a list of tuples `G`
|
[x[0] for x in G]
|
egular expression matching all but 'aa' and 'bb' for string `string`
|
re.findall('-(?!aa-|bb-)([^-]+)', string)
|
egular expression matching all but 'aa' and 'bb'
|
re.findall('-(?!aa|bb)([^-]+)', string)
|
emove false entries from a dictionary `hand`
|
{k: v for k, v in list(hand.items()) if v}
|
Get a dictionary from a dictionary `hand` where the values are prese
|
dict((k, v) for k, v in hand.items() if v)
|
list `L` based on the value of variable 'resultType' for each object in list `L`
|
sorted(L, key=operator.itemgetter('resultType'))
|
a list of objects `s` by a member variable 'resultType'
|
s.sort(key=operator.attrgetter('resultType'))
|
a list of objects 'somelist' where the object has member number variable `resultType`
|
somelist.sort(key=lambda x: x.resultType)
|
join multiple dataframes `d1`, `d2`, and `d3` on column 'name'
|
df1.merge(df2, on='name').merge(df3, on='name')
|
generate random Decimal
|
decimal.Decimal(random.randrange(10000)) / 100
|
list all files of a directory `mypath`
|
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
|
list all files of a directory `mypath`
|
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
|
list all .txt files of a directory /home/adam/
|
print(glob.glob('/home/adam/*.txt'))
|
list all files of a directory somedirectory
|
os.listdir('somedirectory')
|
execute sql query 'INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`
|
cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)
|
get keys with same value in dictionary `d`
|
print([key for key in d if d[key] == 1])
|
get keys with same value in dictionary `d`
|
print([key for key, value in d.items() if value == 1])
|
Get keys from a dictionary 'd' where the value is '1'.
|
print([key for key, value in list(d.items()) if value == 1])
|
eate list of 'size' empty string
|
strs = ['' for x in range(size)]
|
generate pdf file `output_filename` from markdown file `input_filename`
|
with open(input_filename, 'r') as f:
html_text = markdown(f.read(), output_format='html4')
pdfkit.from_string(html_text, output_filename)
|
emove duplicate dict in list `l`
|
[dict(t) for t in set([tuple(d.items()) for d in l])]
|
Set time zone `Europe/Istanbul` in Django
|
TIME_ZONE = 'Europe/Istanbul'
|
ppend `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not ex
|
dates_dict.setdefault(key, []).append(date)
|
Group the values from django model `Article` with group by value `pub_date` and annotate by `title`
|
Article.objects.values('pub_date').annotate(article_count=Count('title'))
|
lear Tkinter Canvas `canvas`
|
canvas.delete('all')
|
alize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`
|
s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])
|
None
|
datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')
|
list `a` using the first dimension of the element as the key to list `b`
|
a.sort(key=lambda x: b.index(x[0]))
|
w to sort a list according to another list?
|
a.sort(key=lambda x_y: b.index(x_y[0]))
|
Save plot `plt` as png file 'filename.png'
|
plt.savefig('filename.png')
|
Save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`
|
plt.savefig('filename.png', dpi=300)
|
get output from process `p1`
|
p1.communicate()[0]
|
w to get output of exe in python script?
|
output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.