question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
8,936,030
Using BeautifulSoup to search html for string
searche in HTML string for elements that have text 'Python'
soup.body.findAll(text='Python')
8,936,030
Using BeautifulSoup to search html for string
BeautifulSoup find string 'Python Jobs' in HTML body `body`
soup.body.findAll(text='Python Jobs')
15,795,525
Python: sorting items in a dictionary by a part of a key?
Sort items in dictionary `d` using the first part of the key after splitting the key
sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))
11,348,347
Find non-common elements in lists
create a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]
set([1, 2, 3]) ^ set([3, 4, 5])
5,430,470
retrieving list items from request.POST in django/python
Get a list values of a dictionary item `pass_id` from post requests in django
request.POST.getlist('pass_id')
11,114,358
How do I remove dicts from a list with duplicate fields in python?
Filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'L'
list(dict((x['id'], x) for x in L).values())
13,078,751
Merge Columns within a DataFrame that have the Same Name
Get pandas GroupBy object with sum over the rows with same column names within dataframe `df`
df.groupby(df.columns, axis=1).sum()
18,789,262
python dict comprehension with two ranges
convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary
dict(zip(list(range(1, 5)), list(range(7, 11))))
8,218,032
How to turn a boolean array into index array in numpy
Get all indexes of boolean numpy array where boolean value `mask` is True
numpy.where(mask)
319,426
case insensitive string comparison
case insensitive comparison of strings `string1` and `string2`
if (string1.lower() == string2.lower()): print('The strings are the same (case insensitive)') else: print('The strings are not the same (case insensitive)')
319,426
case insensitive string comparison
case insensitive string comparison between `string1` and `string2`
if (string1.lower() == string2.lower()): pass
319,426
case insensitive string comparison
case insensitive string comparison between `string1` and `string2`
(string1.lower() == string2.lower())
319,426
case insensitive string comparison
case insensitive string comparison between `first` and `second`
(first.lower() == second.lower())
319,426
case insensitive string comparison
case insensitive comparison between strings `first` and `second`
(first.upper() == second.upper())
5,744,980
Taking the results of a bash command and using it in python
Taking the results of a bash command "awk '{print $10, $11}' test.txt > test2.txt"
os.system("awk '{print $10, $11}' test.txt > test2.txt")
11,303,225
How to remove multiple indexes from a list at the same time?
remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.
del my_list[2:6]
10,716,796
How to convert a string to its Base-10 representation?
convert a string `s` to its base-10 representation
int(s.encode('hex'), 16)
9,618,050
Python regular expression with codons
match regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`
re.findall('TAA(?:[ATGC]{3})+?TAA', seq)
17,457,793
Sorting a set of values
sort a set `s` by numerical value
sorted(s, key=float)
2,269,827
convert an int to a hex string
convert an int 65 to hex string
hex(65)
20,400,135
Simple way to append a pandas series with same index
append a pandas series `b` to the series `a` and get a continuous index
a.append(b).reset_index(drop=True)
20,400,135
Simple way to append a pandas series with same index
simple way to append a pandas series `a` and `b` with same index
pd.concat([a, b], ignore_index=True)
329,886
In Python, is there a concise way to use a list comprehension with multiple iterators?
Get a list of tuples with multiple iterators using list comprehension
[(i, j) for i in range(1, 3) for j in range(1, 5)]
9,849,192
sorting values of python dict using sorted builtin function
reverse sort items in dictionary `mydict` by value
sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)
27,218,543
How can I select 'last business day of the month' in Pandas?
select the last business day of the month for each month in 2014 in pandas
pd.date_range('1/1/2014', periods=12, freq='BM')
15,445,981
How do I disable the security certificate check in Python requests
disable the certificate check in https requests for url `https://kennethreitz.com`
requests.get('https://kennethreitz.com', verify=False)
11,414,596
dropping a row in pandas with dates indexes, python
return dataframe `df` with last row dropped
df.ix[:-1]
3,437,059
string contains substring
check if "blah" is in string `somestring`
if ('blah' not in somestring): pass
3,437,059
string contains substring
check if string `needle` is in `haystack`
if (needle in haystack): pass
3,437,059
string contains substring
check if string "substring" is in string
string.find('substring')
3,437,059
string contains substring method
check if string `s` contains "is"
if (s.find('is') == (-1)): print("No 'is' here!") else: print("Found 'is' in the string.")
36,542,169
Extract first and last row of a dataframe in pandas
extract first and last row of a dataframe `df`
pd.concat([df.head(1), df.tail(1)])
23,351,183
Django - Filter queryset by CharField value length
filter a Django model `MyModel` to have charfield length of max `255`
MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254'])
23,351,183
Django - Filter queryset by CharField value length
Filter queryset for all objects in Django model `MyModel` where texts length are greater than `254`
MyModel.objects.filter(text__regex='^.{254}.*')
28,199,524
Best way to count the number of rows with missing values in a pandas DataFrame
count the number of rows with missing values in a pandas dataframe `df`
sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)
3,728,017
Sorting while preserving order in python
null
sorted(enumerate(a), key=lambda x: x[1])
15,457,504
How to set the font size of a Canvas' text item?
set the font 'Purisa' of size 12 for a canvas' text item `k`
canvas.create_text(x, y, font=('Purisa', 12), text=k)
4,879,641
Python: How to use a list comprehension here?
create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension
[y['baz'] for x in foos for y in x['bar']]
32,743,479
pandas read csv with extra commas in column
read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`
df = pd.read_csv('comma.csv', quotechar="'")
36,296,993
avoiding regex in pandas str.replace
replace string 'in.' with ' in. ' in dataframe `df` column 'a'
df['a'] = df['a'].str.replace('in.', ' in. ')
7,270,321
Finding the index of elements based on a condition using python list comprehension
Get all indexes of a list `a` where each value is greater than `2`
[i for i in range(len(a)) if a[i] > 2]
843,277
check if a variable exists
check if a local variable `myVar` exists
('myVar' in locals())
843,277
check if a variable exists
check if a global variable `myVar` exists
('myVar' in globals())
843,277
check if a variable exists
check if object `obj` has attribute 'attr_name'
hasattr(obj, 'attr_name')
843,277
check if a variable exists
check if a local variable 'myVar' exists
if ('myVar' in locals()): pass
843,277
check if a variable exists
check if a global variable 'myVar' exists
if ('myVar' in globals()): pass
6,243,460
Python lambda function
lambda function that adds two operands
lambda x, y: x + y
5,384,570
What's the shortest way to count the number of items in a generator/iterator?
count the number of items in a generator/iterator `it`
sum(1 for i in it)
18,990,069
how to get tuples from lists using list comprehension in python
get tuples of the corresponding elements from lists `lst` and `lst2`
[(x, lst2[i]) for i, x in enumerate(lst)]
18,990,069
how to get tuples from lists using list comprehension in python
create tuples containing elements that are at the same index of list `lst` and list `lst2`
[(i, j) for i, j in zip(lst, lst2)]
18,990,069
how to get tuples from lists using list comprehension in python
get tuples from lists `lst` and `lst2` using list comprehension in python 2
[(lst[i], lst2[i]) for i in range(len(lst))]
4,296,249
How do I convert a hex triplet to an RGB tuple and back?
convert hex triplet string `rgbstr` to rgb tuple
struct.unpack('BBB', rgbstr.decode('hex'))
10,406,130
Check if something is not in a list
Check if 3 is not in a list [2, 3, 4]
(3 not in [2, 3, 4])
10,406,130
Check if something is not in a list
Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]
((2, 3) not in [(2, 3), (5, 6), (9, 1)])
10,406,130
Check if something is not in a list
Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), "hi"]
((2, 3) not in [(2, 7), (7, 3), 'hi'])
10,406,130
Check if something is not in a list
Check if 3 is not in the list [4,5,6]
(3 not in [4, 5, 6])
35,797,523
Create new list by taking first item from first list, and last item from second list
create a list by appending components from list `a` and reversed list `b` interchangeably
[value for pair in zip(a, b[::-1]) for value in pair]
6,710,684
Remove one column for a numpy array
delete the last column of numpy array `a` and assign resulting array to `b`
b = np.delete(a, -1, 1)
15,271,907
Python mySQL Update, Working but not updating table
commit all the changes after executing a query.
dbb.commit()
40,221,516
How do I join two dataframes based on values in selected columns?
join two dataframes based on values in selected columns
pd.merge(a, b, on=['A', 'B'], how='outer')
24,659,239
How to change QPushButton text and background color
set text color as `red` and background color as `#A3C1DA` in qpushbutton
setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
9,039,961
Finding the average of a list
find the mean of elements in list `l`
sum(l) / float(len(l))
3,252,590
Python: Finding a (string) key in a dictionary that contains a substring
Find all the items from a dictionary `D` if the key contains the string `Light`
[(k, v) for k, v in D.items() if 'Light' in k]
4,508,155
How do I use a MD5 hash (or other binary data) as a key name?
Get a md5 hash from string `thecakeisalie`
k = hashlib.md5('thecakeisalie').hexdigest()
3,925,096
How to get only the last part of a path in Python?
null
os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
2,040,038
Sorting datetime objects while ignoring the year?
sort datetime objects `birthdays` by `month` and `day`
birthdays.sort(key=lambda d: (d.month, d.day))
8,139,797
How do I extract table data in pairs using BeautifulSoup?
extract table data from table `rows` using beautifulsoup
[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
18,723,580
python: rstrip one exact string, respecting order
strip the string `.txt` from anywhere in the string `Boat.txt.txt`
"""Boat.txt.txt""".replace('.txt', '')
26,640,145
Python Pandas: How to get the row names from index of a dataframe?
get a list of the row names from index of a pandas data frame
list(df.index)
26,640,145
Python Pandas: How to get the row names from index of a dataframe?
get the row names from index in a pandas data frame
df.index
13,902,805
List of all unique characters in a string?
create a list of all unique characters in string 'aaabcabccd'
"""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))
13,902,805
List of all unique characters in a string?
get list of all unique characters in a string 'aaabcabccd'
list(set('aaabcabccd'))
13,902,805
List of all unique characters in a string?
null
"""""".join(set('aaabcabccd'))
39,187,788
Find rows with non zero values in a subset of columns in pandas dataframe
find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe
df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]
1,299,855
upload file with Python Mechanize
null
br.form.add_file(open(filename), 'text/plain', filename)
7,128,153
Multiple 'in' operators in Python?
check if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`
all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])
11,269,575
How to hide output of subprocess in Python 2.7
hide output of subprocess `['espeak', text]`
subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)
27,905,295
How to replace NaNs by preceding values in pandas DataFrame?
replace nans by preceding values in pandas dataframe `df`
df.fillna(method='ffill', inplace=True)
31,143,732
How to create range of numbers in Python like in MATLAB
create 4 numbers in range between 1 and 3
print(np.linspace(1, 3, num=4, endpoint=False))
31,143,732
How to create range of numbers in Python like in MATLAB
Create numpy array of `5` numbers starting from `1` with interval of `3`
print(np.linspace(1, 3, num=5))
1,447,575
Symlinks on windows?
create a symlink directory `D:\\testdirLink` for directory `D:\\testdir` with unicode support using ctypes library
kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)
17,277,100
Python: slicing a multi-dimensional array
get a list `slice` of array slices of the first two rows and columns from array `arr`
slice = [arr[i][0:2] for i in range(0, 2)]
23,823,206
Upload files to Google cloud storage from appengine app
upload uploaded file from path '/upload' to Google cloud storage 'my_bucket' bucket
upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')
509,742
Change directory to the directory of a Python script
change directory to the directory of a python script
os.chdir(os.path.dirname(__file__))
817,087
Call a function with argument list in python
call a function with argument list `args`
func(*args)
14,745,022
Pandas DataFrame, how do i split a column into two
split column 'AB' in dataframe `df` into two columns by first whitespace ' '
df['AB'].str.split(' ', 1, expand=True)
14,745,022
Pandas DataFrame, how do i split a column into two
pandas dataframe, how do i split a column 'AB' into two 'A' and 'B' on delimiter ' '
df['A'], df['B'] = df['AB'].str.split(' ', 1).str
2,587,402
Sorting Python list based on the length of the string
sort list `xs` based on the length of its elements
print(sorted(xs, key=len))
2,587,402
Sorting Python list based on the length of the string
sort list `xs` in ascending order of length of elements
xs.sort(lambda x, y: cmp(len(x), len(y)))
2,587,402
Sorting Python list based on the length of the string
sort list of strings `xs` by the length of string
xs.sort(key=lambda s: len(s))
19,939,084
how to plot arbitrary markers on a pandas data series?
plot point marker '.' on series `ts`
ts.plot(marker='.')
14,931,769
get all combination of n binary value
get all combination of n binary values
lst = list(itertools.product([0, 1], repeat=n))
14,931,769
get all combination of n binary value
get all combination of n binary values
lst = map(list, itertools.product([0, 1], repeat=n))
14,931,769
get all combination of n binary value
get all combination of 3 binary values
bin = [0, 1] [(x, y, z) for x in bin for y in bin for z in bin]
14,931,769
get all combination of n binary value
get all combination of 3 binary values
lst = list(itertools.product([0, 1], repeat=3))
20,025,882
Append string to the start of each value in a said column of a pandas dataframe (elegantly)
append string 'str' at the beginning of each value in column 'col' of dataframe `df`
df['col'] = 'str' + df['col'].astype(str)
2,553,354
How to get a variable name as a string in Python?
get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values
dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])
42,387,471
How to add a colorbar for a hist2d plot
add a colorbar to plot `plt` using image `im` on axes `ax`
plt.colorbar(im, ax=ax)
16,734,590
How to get every element in a list of list of lists?
convert nested list 'Cards' into a flat list
[a for c in Cards for b in c for a in b]
575,819
Sorting dictionary keys in python
create a list containing keys of dictionary `d` and sort it alphabetically
sorted(d, key=d.get)