question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
29,902,714
Print the complete string of a pandas dataframe
get value at index `[2, 0]` in dataframe `df`
df.iloc[2, 0]
3,899,980
How to change the font size on a matplotlib plot
change the font size on plot `matplotlib` to 22
matplotlib.rcParams.update({'font.size': 22})
18,837,262
Convert Python dict into a dataframe
converting 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'])
21,022,865
Pandas: Elementwise multiplication of two dataframes
create a dataframe containing the multiplication of element-wise 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)
4,703,390
How to extract a floating number from a string
extract floating number from string 'Current Level: 13.4 db.'
re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')
4,703,390
How to extract a floating number from a string
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')
23,286,254
Convert List to a list of tuples python
pair each element in list `it` 3 times into a tuple
zip(it, it, it)
22,245,171
How to lowercase a python dataframe string column if it has missing values?
lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`
df['x'].str.lower()
10,895,028
python append to array in json object
append 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})
2,133,571
Most Pythonic way to concatenate strings
Concat a list of strings `lst` using string formatting
"""""".join(lst)
15,014,276
Python: Sum values in a dictionary based on condition
sum values greater than 0 in dictionary `d`
sum(v for v in list(d.values()) if v > 0)
32,722,143
Flask application traceback doesn't show up in server log
run flask application `app` in debug mode.
app.run(debug=True)
14,661,701
How to drop a list of rows from Pandas dataframe?
drop rows whose index value in list `[1, 3]` in dataframe `df`
df.drop(df.index[[1, 3]], inplace=True)
18,689,823
pandas DataFrame: replace nan values with average of columns
replace nan values in a pandas data frame with the average of columns
df.apply(lambda x: x.fillna(x.mean()), axis=0)
677,656
How to extract from a list of objects a list of specific attribute?
extract attribute `my_attr` from each object in list `my_list`
[o.my_attr for o in my_list]
16,994,696
python get time stamp on file in mm/dd/yyyy format
python get time stamp on file `file` in '%m/%d/%Y' format
time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
9,323,749
Python: Check if one dictionary is a subset of another larger dictionary
check if dictionary `subset` is a subset of dictionary `superset`
all(item in list(superset.items()) for item in list(subset.items()))
7,768,859
Python: for loop in index assignment
Convert integer elements in list `wordids` to strings
[str(wi) for wi in wordids]
11,621,165
Indexing a pandas dataframe by integer
Reset the indexes of a pandas data frame
df2 = df.reset_index()
10,624,937
Convert datetime object to a String of date only in Python
format datetime in `dt` as string in format `'%m/%d/%Y`
dt.strftime('%m/%d/%Y')
5,180,365
Python Add Comma Into Number String
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))
40,660,956
Sum of Every Two Columns in Pandas dataframe
sum 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')
20,733,827
creating list of random numbers in python
create list `randomList` with 10 random floating point numbers between 0.0 and 1.0
randomList = [random.random() for _ in range(10)]
11,066,874
beautifulsoup can't find href in file using regular expression
find href value that has string 'follow?page' inside it
print(soup.find('a', href=re.compile('.*follow\\?page.*')))
5,917,537
In Python, why won't something print without a newline?
immediately see output of print statement that doesn't end in a newline
sys.stdout.flush()
4,859,292
How to get a random value in python dictionary
get a random key `country` and value `capital` form a dictionary `d`
country, capital = random.choice(list(d.items()))
113,655
Is there a function in python to split a word into a list?
split string `Word to Split` into a list of characters
list('Word to Split')
38,862,349
Regex: How to match words without consecutive vowels?
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)]
11,264,005
Using a RegEx to match IP addresses in Python
Validate IP address using Regex
pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')
1,027,714
How to execute a file within the python interpreter?
execute file 'filename.py'
exec(compile(open('filename.py').read(), 'filename.py', 'exec'))
17,223,174
Returning distinct rows in SQLAlchemy with SQLite
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()
10,857,924
Remove NULL columns in a dataframe Pandas?
remove null columns in a dataframe `df`
df = df.dropna(axis=1, how='all')
12,310,141
Python counting elements of a list within a list
check if all lists in list `L` have three elements of integer 1
all(x.count(1) == 3 for x in L)
13,168,252
Comparing elements between elements in two lists of tuples
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)]
27,966,626
how to clear/delete the Textbox in tkinter python on Ubuntu
clear the textbox `text` in tkinter
tex.delete('1.0', END)
10,664,430
Python convert long to date
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')
41,246,071
How can I start a Python thread FROM C++?
Spawn a process to run python script `myscript.py` in C++
system('python myscript.py')
17,038,639
sorting a list with objects of a class as its items
sort a list `your_list` of class objects by their values for the attribute `anniversary_score`
your_list.sort(key=operator.attrgetter('anniversary_score'))
17,038,639
sorting a list with objects of a class as its items
sort list `your_list` by the `anniversary_score` attribute of each object
your_list.sort(key=lambda x: x.anniversary_score)
34,097,281
How can I convert a tensor into a numpy array in TensorFlow?
convert 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]))))
15,269,161
in Python, How to join a list of tuples into one list?
convert list `a` from being consecutive sequences of tuples into a single sequence of elements
list(itertools.chain(*a))
18,663,026
How do I pythonically set a value in a dictionary if it is None?
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)
30,328,646
Python Pandas : group by in group by and average?
Do group by on `cluster` column in `df` and get its mean
df.groupby(['cluster']).mean()
12,141,150
from list of integers, get number closest to a given value
get number in list `myList` closest in value to number `myNumber`
min(myList, key=lambda x: abs(x - myNumber))
5,858,916
Find array item in a string
check if any of the items in `search` appear in `string`
any(x in string for x in search)
32,792,602
Find string with regular expression in python
search for occurrences of regex pattern `pattern` in string `url`
print(pattern.search(url).group(1))
42,458,734
How do I convert all strings (like "Fault") and into a unique float?
factorize all string values in dataframe `s` into floats
(s.factorize()[0] + 1).astype('float')
11,677,860
Subtract values in one list from corresponding values in another list - Python
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)]
4,793,617
How to derive the week start for a given (iso) weeknumber / year in python
derive the week start for the given week number and year ‘2011, 4, 0’
datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')
5,306,079
Python: How do I convert an array of strings to an array of numbers?
convert a list of strings `['1', '-1', '1']` to a list of numbers
map(int, ['1', '-1', '1'])
18,684,397
How to create datetime object from "16SEP2012" in python
create datetime object from "16sep2012"
datetime.datetime.strptime('16Sep2012', '%d%b%Y')
5,503,925
How do I use a dictionary to update fields in Django models?
update fields in Django model `Book` with arguments in dictionary `d` where primary key is equal to `pk`
Book.objects.filter(pk=pk).update(**d)
5,503,925
How do I use a dictionary to update fields in Django models?
update the fields in django model `Book` using dictionary `d`
Book.objects.create(**d)
5,229,425
Precision in python
print a digit `your_number` with exactly 2 digits after decimal
print('{0:.2f}'.format(your_number))
13,496,087
Python: How to generate a 12-digit random number?
generate a 12-digit random number
random.randint(100000000000, 999999999999)
13,496,087
Python: How to generate a 12-digit random number?
generate a random 12-digit number
int(''.join(str(random.randint(0, 9)) for _ in range(12)))
13,496,087
Python: How to generate a 12-digit random number?
generate a random 12-digit number
"""""".join(str(random.randint(0, 9)) for _ in range(12))
13,496,087
Python: How to generate a 12-digit random number?
generate a 12-digit random number
'%0.12d' % random.randint(0, 999999999999)
10,996,140
How to remove specific elements in a numpy array
remove specific elements in a numpy array `a`
numpy.delete(a, index)
12,987,178
Sort a list based on dictionary values in python?
sort list `trial_list` based on values of dictionary `trail_dict`
sorted(trial_list, key=lambda x: trial_dict[x])
510,357
read a single character from the user
read a single character from stdin
sys.stdin.read(1)
40,094,588
How to get a list of matchable characters from a regex class
get a list of characters in string `x` matching regex pattern `pattern`
print(re.findall(pattern, x))
28,780,956
how to get the context of a search in BeautifulSoup?
get the context of a search by keyword 'My keywords' in beautifulsoup `soup`
k = soup.find(text=re.compile('My keywords')).parent.text
19,585,280
Convert a row in pandas into list
convert rows in pandas data frame `df` into list
df.apply(lambda x: x.tolist(), axis=1)
12,575,421
Convert a 1D array to a 2D array in numpy
convert a 1d `A` array to a 2d array `B`
B = np.reshape(A, (-1, 2))
30,241,279
Flask - How to make an app externally visible through a router?
run app `app` on host '192.168.0.58' and port 9000 in Flask
app.run(host='192.168.0.58', port=9000, debug=False)
15,740,236
Stdout encoding in python
encode unicode string '\xc5\xc4\xd6' to utf-8 code
print('\xc5\xc4\xd6'.encode('UTF8'))
12,440,342
Best way to get the nth element of each tuple from a list of tuples in Python
get the first element of each tuple from a list of tuples `G`
[x[0] for x in G]
39,600,161
Regular expression matching all but a string
regular expression matching all but 'aa' and 'bb' for string `string`
re.findall('-(?!aa-|bb-)([^-]+)', string)
39,600,161
Regular expression matching all but a string
regular expression matching all but 'aa' and 'bb'
re.findall('-(?!aa|bb)([^-]+)', string)
15,158,599
Removing entries from a dictionary based on values
remove false entries from a dictionary `hand`
{k: v for k, v in list(hand.items()) if v}
15,158,599
Removing entries from a dictionary based on values
Get a dictionary from a dictionary `hand` where the values are present
dict((k, v) for k, v in hand.items() if v)
2,338,531
Python sorting - A list of objects
sort list `L` based on the value of variable 'resultType' for each object in list `L`
sorted(L, key=operator.itemgetter('resultType'))
2,338,531
Python sorting - A list of objects
sort a list of objects `s` by a member variable 'resultType'
s.sort(key=operator.attrgetter('resultType'))
2,338,531
Python sorting - A list of objects
sort a list of objects 'somelist' where the object has member number variable `resultType`
somelist.sort(key=lambda x: x.resultType)
23,668,427
pandas joining multiple dataframes on columns
join multiple dataframes `d1`, `d2`, and `d3` on column 'name'
df1.merge(df2, on='name').merge(df3, on='name')
439,115
random Decimal in python
generate random Decimal
decimal.Decimal(random.randrange(10000)) / 100
3,207,219
list all files of a directory
list all files of a directory `mypath`
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
3,207,219
list all files of a directory
list all files of a directory `mypath`
f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break
3,207,219
list all files of a directory
list all ".txt" files of a directory "/home/adam/"
print(glob.glob('/home/adam/*.txt'))
3,207,219
list all files of a directory
list all files of a directory "somedirectory"
os.listdir('somedirectory')
8,134,602
psycopg2: insert multiple rows with one query
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)
24,958,010
get key by value in dictionary with same value in python?
get keys with same value in dictionary `d`
print([key for key in d if d[key] == 1])
24,958,010
get key by value in dictionary with same value in python?
get keys with same value in dictionary `d`
print([key for key, value in d.items() if value == 1])
24,958,010
get key by value in dictionary with same value in python?
Get keys from a dictionary 'd' where the value is '1'.
print([key for key, value in list(d.items()) if value == 1])
6,376,886
What is the best way to create a string array in python?
create list of 'size' empty strings
strs = ['' for x in range(size)]
4,135,344
generate pdf from markdown file
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)
9,427,163
Remove duplicate dict in list in Python
remove duplicate dict in list `l`
[dict(t) for t in set([tuple(d.items()) for d in l])]
29,311,354
How to set the timezone in Django?
Set time zone `Europe/Istanbul` in Django
TIME_ZONE = 'Europe/Istanbul'
26,367,812
Appending to list in Python dictionary
append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist
dates_dict.setdefault(key, []).append(date)
1,908,741
How to do this GROUP BY query in Django's ORM with annotate and aggregate
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'))
15,839,491
How to clear Tkinter Canvas?
clear Tkinter Canvas `canvas`
canvas.delete('all')
39,816,795
How to add a specific number of characters to the end of string in Pandas?
Initialize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`
s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])
969,285
How do I translate a ISO 8601 datetime string into a Python datetime object?
None
datetime.datetime.strptime('2007-03-04T21:08:12', '%Y-%m-%dT%H:%M:%S')
12,814,667
How to sort a list according to another list?
sort list `a` using the first dimension of the element as the key to list `b`
a.sort(key=lambda x: b.index(x[0]))
12,814,667
How to sort a list according to another list?
null
a.sort(key=lambda x_y: b.index(x_y[0]))
39,870,642
Matplotlib - How to plot a high resolution graph?
Save plot `plt` as png file 'filename.png'
plt.savefig('filename.png')
39,870,642
Matplotlib - How to plot a high resolution graph?
Save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`
plt.savefig('filename.png', dpi=300)
748,028
How to get output of exe in python script?
get output from process `p1`
p1.communicate()[0]
748,028
How to get output of exe in python script?
null
output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]