question_id
int64
1.48k
42.8M
intent
stringlengths
11
122
rewritten_intent
stringlengths
4
183
snippet
stringlengths
2
232
42,394,627
python How do you sort list by occurrence with out removing elements from the list?
sort list `lst` based on each element's number of occurrences
sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))
6,018,916
Find max length of each column in a list of lists
Get the value with the maximum length in each column in array `foo`
[max(len(str(x)) for x in line) for line in zip(*foo)]
39,607,540
Count the number of Occurrence of Values based on another column
get the count of each unique value in column `Country` of dataframe `df` and store in column `Sum of Accidents`
df.Country.value_counts().reset_index(name='Sum of Accidents')
13,114,512
Calculating difference between two rows in Python / Pandas
calculat the difference between each row and the row previous to it in dataframe `data`
data.set_index('Date').diff()
3,392,354
python: append values to a set
append values `[3, 4]` to a set `a`
a.update([3, 4])
7,154,739
How can I get an array of alternating values in python?
set every two-stride far element to -1 starting from second element in array `a`
a[1::2] = -1
26,720,916
Faster way to rank rows in subgroups in pandas dataframe
Get rank of rows from highest to lowest of dataframe `df`, grouped by value in column `group`, according to value in column `value`
df.groupby('group')['value'].rank(ascending=False)
8,153,631
Js Date object to python datetime
convert js date object 'Tue, 22 Nov 2011 06:00:00 GMT' to python datetime
datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
33,769,531
Python: Converting from binary to String
Convert a binary value '1633837924' to string
struct.pack('<I', 1633837924)
8,243,188
Inserting a string into a list without getting split into characters
append string `foo` to list `list`
list.append('foo')
8,243,188
Inserting a string into a list without getting split into characters
insert string `foo` at position `0` of list `list`
list.insert(0, 'foo')
3,296,499
Case insensitive dictionary search with Python
convert keys in dictionary `thedict` into case insensitive
theset = set(k.lower() for k in thedict)
4,008,546
How to pad with n characters in Python
pad 'dog' up to a length of 5 characters with 'x'
"""{s:{c}^{n}}""".format(s='dog', n=5, c='x')
4,843,173
How to check if type of a variable is string?
check if type of variable `s` is a string
isinstance(s, str)
4,843,173
How to check if type of a variable is string?
check if type of a variable `s` is string
isinstance(s, str)
3,494,906
How do I merge a list of dicts into a single dict?
Convert list of dictionaries `L` into a flat dictionary
dict(pair for d in L for pair in list(d.items()))
3,494,906
How do I merge a list of dicts into a single dict?
merge a list of dictionaries in list `L` into a single dict
{k: v for d in L for k, v in list(d.items())}
13,636,592
How to sort a Pandas DataFrame according to multiple criteria?
sort a pandas data frame according to column `Peak` in ascending and `Weeks` in descending order
df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)
13,636,592
How to sort a Pandas DataFrame according to multiple criteria?
sort a pandas data frame by column `Peak` in ascending and `Weeks` in descending order
df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)
1,015,142
Running Python code contained in a string
run the code contained in string "print('Hello')"
eval("print('Hello')")
35,883,459
Creating a list of dictionaries in python
creating a list of dictionaries [{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
35,883,459
Creating a list of dictionaries in python
null
[{'A': 1, 'C': 4, 'B': 2, 'D': 4}, {'A': 1, 'C': 4, 'B': 1, 'D': 5}]
8,249,836
how to get all possible combination of items from 2-dimensional list in python?
get all possible combination of items from 2-dimensional list `a`
list(itertools.product(*a))
32,751,229
Pandas sum by groupby, but exclude certain columns
Get sum of values of columns 'Y1961', 'Y1962', 'Y1963' after group by on columns "Country" and "Item_code" in dataframe `df`.
df.groupby(['Country', 'Item_Code'])[['Y1961', 'Y1962', 'Y1963']].sum()
9,962,293
Python turning a list into a list of tuples
create list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuples
done = [(el, x) for el in [a, b, c, d]]
11,620,914
Removing nan values from an array
remove Nan values from array `x`
x = x[numpy.logical_not(numpy.isnan(x))]
26,724,275
Removing the first folder in a path
remove first directory from path '/First/Second/Third/Fourth/Fifth'
os.path.join(*x.split(os.path.sep)[2:])
12,723,751
Replacing instances of a character in a string
Replace `;` with `:` in a string `line`
line = line.replace(';', ':')
7,323,859
Python - How to call bash commands with pipe?
call bash command 'tar c my_dir | md5sum' with pipe
subprocess.call('tar c my_dir | md5sum', shell=True)
10,618,586
hex string to character in python
Convert a hex string `437c2123 ` according to ascii value.
"""437c2123""".decode('hex')
8,586,738
Get required fields from Document in mongoengine?
Get a list of all fields in class `User` that are marked `required`
[k for k, v in User._fields.items() if v.required]
19,973,489
Pandas remove column by index
remove column by index `[:, 0:2]` in dataframe `df`
df = df.ix[:, 0:2]
19,555,472
Change a string of integers separated by spaces to a list of int
change a string of integers `x` separated by spaces to a list of int
x = map(int, x.split())
19,555,472
Change a string of integers separated by spaces to a list of int
convert a string of integers `x` separated by spaces to a list of integers
x = [int(i) for i in x.split()]
21,691,126
Find and click an item from 'onclick' partial value
find element by css selector "input[onclick*='1 Bedroom Deluxe']"
driver.find_element_by_css_selector("input[onclick*='1 Bedroom Deluxe']")
25,991,612
Python / Remove special character from string
null
re.sub('[^a-zA-Z0-9-_*.]', '', my_string)
21,684,346
How to display a pdf that has been downloaded in python
display a pdf file that has been downloaded as `my_pdf.pdf`
webbrowser.open('file:///my_pdf.pdf')
3,160,752
Removing backslashes from a string in Python
replace backslashes in string `result` with empty string ''
result = result.replace('\\', '')
3,160,752
Removing backslashes from a string in Python
remove backslashes from string `result`
result.replace('\\', '')
42,172,204
Replace value in any column in pandas dataframe
replace value '-' in any column of pandas dataframe to "NaN"
df.replace('-', 'NaN')
3,743,222
How do I convert datetime to date (in Python)?
convert datetime object to date object in python
datetime.datetime.now().date()
3,743,222
How do I convert datetime to date (in Python)?
null
datetime.datetime.now().date()
10,408,927
How to get all sub-elements of an element tree with Python ElementTree?
get all sub-elements of an element `a` in an elementtree
[elem.tag for elem in a.iter()]
10,408,927
How to get all sub-elements of an element tree with Python ElementTree?
get all sub-elements of an element tree `a` excluding the root element
[elem.tag for elem in a.iter() if elem is not a]
5,749,195
How can I split and parse a string in Python?
null
"""2.7.0_bf4fda703454""".split('_')
42,364,593
Python - Move elements in a list of dictionaries to the end of the list
move dictionaries in list `lst` to the end of the list if value of key 'language' in each dictionary is not equal to 'en'
sorted(lst, key=lambda x: x['language'] != 'en')
35,253,971
How to check if all values of a dictionary are 0, in Python?
check if all values of a dictionary `your_dict` are zero `0`
all(value == 0 for value in list(your_dict.values()))
9,550,867
Python Pandas Pivot Table
produce a pivot table as dataframe using column 'Y' in datafram `df` to form the axes of the resulting dataframe
df.pivot_table('Y', rows='X', cols='X2')
730,764
do a try-except without handling the exception
call `doSomething()` in a try-except without handling the exception
try: doSomething() except: pass
730,764
do a try-except without handling the exception
call `doSomething()` in a try-except without handling the exception
try: doSomething() except Exception: pass
24,841,306
Python - Sum 4D Array
get a sum of 4d array `M`
M.sum(axis=0).sum(axis=0)
7,238,226
Python datetime to microtime
Convert a datetime object `dt` to microtime
time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
40,156,469
How to check if any value of a column is in a range in Pandas?
select all rows in dataframe `df` where the values of column 'columnX' is bigger than or equal to `x` and smaller than or equal to `y`
df[(x <= df['columnX']) & (df['columnX'] <= y)]
4,174,941
sort a list of lists by a specific index of the inner list
sort a list of lists `L` by index 2 of the inner list
sorted(L, key=itemgetter(2))
4,174,941
sort a list of lists by a specific index of the inner list
sort a list of lists `l` by index 2 of the inner list
l.sort(key=(lambda x: x[2]))
4,174,941
sort a list of lists by a specific index
sort list `l` by index 2 of the item
sorted(l, key=(lambda x: x[2]))
4,174,941
sort a list of lists by a specific index
sort a list of lists `list_to_sort` by indices 2,0,1 of the inner list
sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))
36,381,230
How to find row of 2d array in 3d numpy array
find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'
np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))
18,470,323
How to select only specific columns from a DataFrame with MultiIndex columns?
From multiIndexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`
data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]
18,470,323
How to select only specific columns from a DataFrame with MultiIndex columns?
select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns
data.loc[:, ([('one', 'a'), ('one', 'c'), ('two', 'a'), ('two', 'c')])]
18,663,644
How to account for accent characters for regex in Python?
match a sharp, followed by letters (including accent characters) in string `str1` using a regex
hashtags = re.findall('#(\\w+)', str1, re.UNICODE)
2,759,067
Rename Files
Rename file from `src` to `dst`
os.rename(src, dst)
10,258,584
How to get text for a root element using lxml?
Get all texts and tags from a tag `strong` from etree tag `some_tag` using lxml
print(etree.tostring(some_tag.find('strong')))
12,337,583
Saving dictionary whose keys are tuples with json, python
Serialize dictionary `data` and its keys to a JSON formatted string
json.dumps({str(k): v for k, v in data.items()})
20,205,455
How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?
parse UTF-8 encoded HTML response `response` to BeautifulSoup object
soup = BeautifulSoup(response.read().decode('utf-8'))
39,998,424
How to delete a file without an extension?
delete file `filename`
os.remove(filename)
29,471,884
Get the immediate minimum among a list of numbers in python
get the next value greatest to `2` from a list of numbers `num_list`
min([x for x in num_list if x > 2])
39,602,824
pandas: replace string with another string
Replace each value in column 'prod_type' of dataframe `df` with string 'responsive'
df['prod_type'] = 'responsive'
40,620,804
How do I sort a list with positives coming before negatives with values sorted respectively?
sort list `lst` with positives coming before negatives with values sorted respectively
sorted(lst, key=lambda x: (x < 0, x))
546,321
How do I calculate the date six months from the current date
get the date 6 months from today
six_months = (date.today() + relativedelta(months=(+ 6)))
546,321
How do I calculate the date six months from the current date
get the date 1 month from today
(date(2010, 12, 31) + relativedelta(months=(+ 1)))
546,321
How do I calculate the date six months from the current date
get the date 2 months from today
(date(2010, 12, 31) + relativedelta(months=(+ 2)))
546,321
calculate the date six months from the current date
calculate the date six months from the current date
print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat())
42,352,887
Finding The Biggest Key In A Python Dictionary
get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight'
sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)
7,429,118
how to get all the values from a numpy array excluding a certain index?
get all the values from a numpy array `a` excluding index 3
a[np.arange(len(a)) != 3]
3,895,424
what is a quick way to delete all elements from a list that do not satisfy a constraint?
delete all elements from a list `x` if a function `fn` taking value as parameter returns `0`
[x for x in lst if fn(x) != 0]
15,752,422
Python Pandas - Date Column to Column index
set dataframe `df` index using column 'month'
df.set_index('month')
1,532,810
How to read lines from a file into a multidimensional array (or an array of lists) in python
read lines from a csv file `./urls-eu.csv` into a list of lists `arr`
arr = [line.split(',') for line in open('./urls-eu.csv')]
15,248,272
python list comprehension with multiple 'if's
list comprehension that produces integers between 11 and 19
[i for i in range(100) if i > 10 if i < 20]
18,116,235
Removing letters from a list of both numbers and letters
Get only digits from a string `strs`
"""""".join([c for c in strs if c.isdigit()])
17,038,426
splitting a string based on tab in the file
split a string `yas` based on tab '\t'
re.split('\\t+', yas.rstrip('\t'))
3,809,265
numpy matrix multiplication
scalar multiply matrix `a` by `b`
(a.T * b).T
275,018
remove (chomp) a newline
remove trailing newline in string "test string\n"
'test string\n'.rstrip()
275,018
remove (chomp) a newline
remove trailing newline in string 'test string \n\n'
'test string \n\n'.rstrip('\n')
275,018
remove (chomp) a newline
remove newline in string `s`
s.strip()
275,018
remove (chomp) a newline
remove newline in string `s` on the right side
s.rstrip()
275,018
remove (chomp) a newline
remove newline in string `s` on the left side
s.lstrip()
275,018
remove (chomp) a newline
remove newline in string 'Mac EOL\r'
'Mac EOL\r'.rstrip('\r\n')
275,018
remove (chomp) a newline
remove newline in string 'Windows EOL\r\n' on the right side
'Windows EOL\r\n'.rstrip('\r\n')
275,018
remove (chomp) a newline
remove newline in string 'Unix EOL\n' on the right side
'Unix EOL\n'.rstrip('\r\n')
275,018
remove (chomp) a newline
remove newline in string "Hello\n\n\n" on the right side
'Hello\n\n\n'.rstrip('\n')
18,551,752
Python - split sentence after words but with maximum of n characters in result
split string `text` into chunks of 16 characters each
re.findall('.{,16}\\b', text)
21,360,028
NumPy List Comprehension Syntax
Get a list comprehension in list of lists `X`
[[X[i][j] for j in range(len(X[i]))] for i in range(len(X))]
11,174,790
Convert unicode string to byte string
convert unicode string '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' to byte string
'\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0'.encode('latin-1')
13,353,233
Best way to split a DataFrame given an edge
split dataframe `df` where the value of column `a` is equal to 'B'
df.groupby((df.a == 'B').shift(1).fillna(0).cumsum())
3,040,904
Save JSON outputed from a URL to a file
save json output from a url ‘http://search.twitter.com/search.json?q=hi’ to file ‘hi.json’ in Python 2
urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')
4,588,628
Find indices of elements equal to zero from numpy array
Find indices of elements equal to zero from numpy array `x`
numpy.where((x == 0))[0]
3,804,727
python, subprocess: reading output from subprocess
flush output of python print
sys.stdout.flush()
961,632
Converting integer to string
convert `i` to string
str(i)
961,632
Converting integer to string
convert `a` to string
a.__str__()