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