question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
29,422,691
How to count the number of occurences of `None` in a list?
print the number of occurences of not `none` in a list `lst` in Python 2
print(len([x for x in lst if x is not None]))
19,745,091
Accessing dictionary by key in Django template
lookup dictionary key `key1` in Django template `json`
{{json.key1}}
12,897,374
Get unique values from a list in python
remove duplicates from list `myset`
mynewlist = list(myset)
12,897,374
Get unique values from a list in python
get unique values from the list `['a', 'b', 'c', 'd']`
set(['a', 'b', 'c', 'd'])
15,571,267
Python: A4 size for a plot
set size of `figure` to landscape A4 i.e. `11.69, 8.27` inches
figure(figsize=(11.69, 8.27))
7,253,803
How to get everything after last slash in a URL?
get every thing after last `/`
url.rsplit('/', 1)
7,253,803
How to get everything after last slash in a URL?
get everything after last slash in a url stored in variable 'url'
url.rsplit('/', 1)[-1]
13,223,737
how to read a file in other directory in python
open file '5_1.txt' in directory `direct`
x_file = open(os.path.join(direct, '5_1.txt'), 'r')
5,501,641
How to create a list with the characters of a string?
create a list with the characters of a string `5+6`
list('5+6')
33,711,985
Flattening a list of NumPy arrays?
concatenate a list of numpy arrays `input_list` together into a flattened list of values
np.concatenate(input_list).ravel().tolist()
11,351,874
Converting a dict into a list
convert dictionary `dict` into a flat list
print([y for x in list(dict.items()) for y in x])
11,351,874
Converting a dict into a list
Convert a dictionary `dict` into a list with key and values as list items.
[y for x in list(dict.items()) for y in x]
962,619
How to pull a random record using Django's ORM?
get a random record from model 'MyModel' using django's orm
MyModel.objects.order_by('?').first()
20,796,355
change current working directory in python
change current working directory to directory 'chapter3'
os.chdir('chapter3')
20,796,355
change current working directory in python
change current working directory
os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
20,796,355
change current working directory in python
change current working directory
os.chdir('.\\chapter3')
974,678
How to create single Python dict from a list of dicts by summing values with common keys?
create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`
dict((key, sum(d[key] for d in dictList)) for key in dictList[0])
17,618,981
How to sort pandas data frame using values from several columns?
sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order
df.sort(['c1', 'c2'], ascending=[True, True])
4,004,550
Converting string series to float list
Converting string lists `s` to float list
floats = [float(x) for x in s.split()]
4,004,550
Converting string series to float list
Converting string lists `s` to float list
floats = map(float, s.split())
10,839,719
How to set "step" on axis X in my figure in matplotlib python 2.6.6?
set labels `[1, 2, 3, 4, 5]` on axis X in plot `plt`
plt.xticks([1, 2, 3, 4, 5])
1,450,393
read from stdin
read line by line from stdin
for line in fileinput.input(): pass
1,450,393
read from stdin
read line by line from stdin
for line in sys.stdin: pass
8,214,932
How to check if a value exists in a dictionary (python)
check if string `one` exists in the values of dictionary `d`
'one' in list(d.values())
8,214,932
How to check if a value exists in a dictionary (python)
Check if value 'one' is among the values of dictionary `d`
'one' in iter(d.values())
12,557,612
Calling a parent class constructor from a child class in python
call parent class `Instructor` of child class constructor
super(Instructor, self).__init__(name, year)
15,183,084
how to create a dictionary using two lists in python?
create a dictionary using two lists`x` and `y`
dict(zip(x, y))
10,915,391
Sorting a list of dicts by dict values
sort a list of dictionaries `a` by dictionary values in descending order
sorted(a, key=lambda i: list(i.values())[0], reverse=True)
10,915,391
Sorting a list of dicts by dict values
sorting a list of dictionary `a` by values in descending order
sorted(a, key=dict.values, reverse=True)
39,159,475
pandas: how to do multiple groupby-apply operations
Use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`
df.groupby(level=0).agg(['sum', 'count', 'std'])
20,585,920
How to add multiple values to a dictionary key in python?
for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key
a.setdefault('somekey', []).append('bob')
11,692,613
Python - sum values in dictionary
sum values in list of dictionaries `example_list` with key 'gold'
sum(item['gold'] for item in example_list)
11,692,613
Python - sum values in dictionary
get a sum of all values from key `gold` in a list of dictionary `example_list`
sum([item['gold'] for item in example_list])
11,692,613
Python - sum values in dictionary
Get all the values in key `gold` summed from a list of dictionary `myLIst`
sum(item['gold'] for item in myLIst)
2,918,362
writing string to a file on a new line everytime?
writing string 'text to write\n' to file `f`
f.write('text to write\n')
2,918,362
writing string to a file on a new line everytime?
Write a string `My String` to a file `file` including new line character
file.write('My String\n')
14,358,567
Finding consecutive segments in a pandas data frame
find consecutive segments from a column 'A' in a pandas data frame 'df'
df.reset_index().groupby('A')['index'].apply(np.array)
1,270,951
Python - how to refer to relative paths of resources when working with code repository
get a relative path of file 'my_file' into variable `fn`
fn = os.path.join(os.path.dirname(__file__), 'my_file')
59,825
How to retrieve an element from a set without removing it?
retrieve an element from a set `s` without removing it
e = next(iter(s))
5,486,725
How to execute a command prompt command from python
execute a command in the command prompt to list directory contents of the c drive `c:\\'
os.system('dir c:\\')
5,218,948
How to auto-scroll a gtk.scrolledwindow?
Make a auto scrolled window to the end of the list in gtk
self.treeview.connect('size-allocate', self.treeview_changed)
9,542,738
Python: Find in list
check if 3 is inside list `[1, 2, 3]`
3 in [1, 2, 3]
10,541,640
Convert date format python
Represent DateTime object '10/05/2012' with format '%d/%m/%Y' into format '%Y-%m-%d'
datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')
7,262,828
python : how to convert string literal to raw string literal?
convert a string literal `s` with values `\\` to raw string literal
s = s.replace('\\', '\\\\')
6,086,047
Get output of python script from within python script
get output of script `proc`
print(proc.communicate()[0])
41,946,927
Getting pandas dataframe from list of nested dictionaries
create a pandas data frame from list of nested dictionaries `my_list`
pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T
21,164,910
Delete Column in Pandas based on Condition
delete all columns in DataFrame `df` that do not hold a non-zero value in its records
df.loc[:, ((df != 0).any(axis=0))]
20,183,069
How to sort multidimensional array by column?
sort a multidimensional array `a` by column with index 1
sorted(a, key=lambda x: x[1])
9,905,471
string to list conversion in python
split string `s` to list conversion by ','
[x.strip() for x in s.split(',')]
9,089,043
Get list item by attribute in Python
Get a list of items in the list `container` with attribute equal to `value`
items = [item for item in container if item.attribute == value]
3,820,312
Python: Write a list of tuples to a file
create a file 'filename' with each tuple in the list `mylist` written to a line
open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))
17,407,691
Python regex to match multiple times
Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`
pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)
8,369,219
How do I read a text file into a string variable in Python
read a text file 'very_Important.txt' into a string variable `str`
str = open('very_Important.txt', 'r').read()
33,680,914
Grouping dataframes in pandas?
Return values for column `C` after group by on column `A` and `B` in dataframe `df`
df.groupby(['A', 'B'])['C'].unique()
3,277,503
read a file line by line into a list
read file `fname` line by line into a list `content`
with open(fname) as f: content = f.readlines()
3,277,503
read a file line by line into a list
read file 'filename' line by line into a list `lines`
with open('filename') as f: lines = f.readlines()
3,277,503
read a file line by line into a list
read file 'filename' line by line into a list `lines`
lines = [line.rstrip('\n') for line in open('filename')]
3,277,503
read a file line by line into a list
read file "file.txt" line by line into a list `array`
with open('file.txt', 'r') as ins: array = [] for line in ins: array.append(line)
17,134,716
Convert DataFrame column type from string to datetime
convert the dataframe column 'col' from string types to datetime types
df['col'] = pd.to_datetime(df['col'])
41,251,391
Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?
get a list of the keys in each dictionary in a dictionary of dictionaries `foo`
[k for d in list(foo.values()) for k in d]
7,173,850
Possible to get user input without inserting a new line?
get user input using message 'Enter name here: ' and insert it to the first placeholder in string 'Hello, {0}, how do you do?'
print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))
41,386,443
Create Pandas DataFrame from txt file with specific pattern
create pandas data frame `df` from txt file `filename.txt` with column `Region Name` and separator `;`
df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])
34,962,104
Pandas: How can I use the apply() function for a single column?
null
df['a'] = df['a'].apply(lambda x: x + 1)
30,015,665
How to check whether the system is FreeBSD in a python script?
get the platform OS name
platform.system()
17,474,211
How to sort python list of strings of numbers
sort list `a` in ascending order based on its elements' float values
a = sorted(a, key=lambda x: float(x))
6,633,678
Finding words after keyword in python
finding words in string `s` after keyword 'name'
re.search('name (.*)', s)
12,345,387
Removing _id element from Pymongo results
Find all records from collection `collection` without extracting mongo id `_id`
db.collection.find({}, {'_id': False})
903,853
How do you extract a column from a multi-dimensional array?
Get all the second values from a list of lists `A`
[row[1] for row in A]
903,853
How do you extract a column from a multi-dimensional array?
extract first column from a multi-dimensional array `a`
[row[0] for row in a]
9,758,959
Python - how to sort a list of numerical values in ascending order
sort list `['10', '3', '2']` in ascending order based on the integer value of its elements
sorted(['10', '3', '2'], key=int)
3,328,012
How can I tell if a file is a descendant of a given directory?
check if file `filename` is descendant of directory '/the/dir/'
os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'
8,122,079
Python: How to check a string for substrings from a list?
check if any element of list `substring_list` are in string `string`
any(substring in string for substring in substring_list)
19,961,490
Construct pandas DataFrame from list of tuples
construct pandas dataframe from a list of tuples
df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])
27,589,325
How to find and replace nth occurence of word in a sentence using python regular expression?
find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'
re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)
27,589,325
How to find and replace nth occurence of word in a sentence using python regular expression?
find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's'
re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)
4,287,209
Sort list of strings by integer suffix in python
sort list of strings in list `the_list` by integer suffix
sorted(the_list, key=lambda k: int(k.split('_')[1]))
4,287,209
Sort list of strings by integer suffix in python
sort list of strings `the_list` by integer suffix before "_"
sorted(the_list, key=lambda x: int(x.split('_')[1]))
27,659,153
How to group similar items in a list?
make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character
[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]
27,659,153
How to group similar items in a list?
null
[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]
4,618,373
How do I use the HTMLUnit driver with Selenium from Python?
Load the url `http://www.google.com` in selenium webdriver `driver`
driver.get('http://www.google.com')
14,043,080
Using Python's datetime module, can I get the year that UTC-11 is currently in?
using python's datetime module, get the year that utc-11 is currently in
(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year
33,435,418
How to find the difference between 3 lists that may have duplicate numbers
Get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values
Counter([1, 2, 2, 2, 3]) - Counter([1, 2])
3,662,142
How to remove tags from a string in python using regular expressions? (NOT in HTML)
remove tags from a string `mystring`
re.sub('<[^>]*>', '', mystring)
200,738
How can I unpack binary hex formatted data in Python?
encode string `data` as `hex`
data.encode('hex')
10,040,143
How to do a less than or equal to filter in Django queryset?
filter `Users` by field `userprofile` with level greater than or equal to `0`
User.objects.filter(userprofile__level__gte=0)
11,924,135
How to use Beautiful Soup to find a tag with changing id?
BeautifulSoup find a tag whose id ends with string 'para'
soup.findAll(id=re.compile('para$'))
11,924,135
How to use Beautiful Soup to find a tag with changing id?
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_"]')
4,915,920
How to delete an item in a list if it exists?
delete an item `thing` in a list `some_list` if it exists
cleaned_list = [x for x in some_list if x is not thing]
70,797
user input and commandline arguments
print "Please enter something: " to console, and read user input to `var`
var = input('Please enter something: ')
4,641,765
Add to integers in a list
append 4 to list `foo`
foo.append(4)
4,641,765
Add to integers in a list
append a list [8, 7] to list `foo`
foo.append([8, 7])
4,641,765
Add to integers in a list
insert 77 to index 2 of list `x`
x.insert(2, 77)
11,837,979
Removing white space around a saved image in matplotlib
remove white space padding around a saved image `test.png` in matplotlib
plt.savefig('test.png', bbox_inches='tight')
1,720,421
concatenate lists
concatenate lists `listone` and `listtwo`
(listone + listtwo)
1,720,421
concatenate lists
iterate items in lists `listone` and `listtwo`
for item in itertools.chain(listone, listtwo): pass
22,086,116
how do you filter pandas dataframes by multiple columns
create dataframe `males` containing data of dataframe `df` where column `Gender` is equal to 'Male' and column `Year` is equal to 2014
males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]
19,095,796
How to print backslash with Python?
print backslash
print('\\')
17,097,236
How to replace values with None in Pandas data frame in Python?
replace '-' in pandas dataframe `df` with `np.nan`
df.replace('-', np.nan)
13,411,544
Delete column from pandas DataFrame
delete column 'column_name' from dataframe `df`
df = df.drop('column_name', 1)
13,411,544
Delete column from pandas DataFrame
delete 1st, 2nd and 4th columns from dataframe `df`
df.drop(df.columns[[0, 1, 3]], axis=1)