text
stringlengths
4
1.08k
Delete an element 0 from a dictionary `a`,{i: a[i] for i in a if (i != 0)}
"Delete an element ""hello"" from a dictionary `lol`",lol.pop('hello')
Delete an element with key `key` dictionary `r`,del r[key]
solve for the least squares' solution of matrices `a` and `b`,"np.linalg.solve(np.dot(a.T, a), np.dot(a.T, b))"
split dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)"
loop through 0 to 10 with step 2,"for i in range(0, 10, 2):
pass"
loop through `mylist` with step 2,"for i in mylist[::2]:
pass"
lowercase string values with key 'content' in a list of dictionaries `messages`,[{'content': x['content'].lower()} for x in messages]
convert a list `my_list` into string with values separated by spaces,""""""" """""".join(my_list)"
replace each occurrence of the pattern '(http://\\S+|\\S*[^\\w\\s]\\S*)' within `a` with '',"re.sub('(http://\\S+|\\S*[^\\w\\s]\\S*)', '', a)"
check if string `str` is palindrome,str(n) == str(n)[::-1]
upload binary file `myfile.txt` with ftplib,"ftp.storbinary('STOR myfile.txt', open('myfile.txt', 'rb'))"
remove all characters from string `stri` upto character 'I',"re.sub('.*I', 'I', stri)"
"parse a comma-separated string number '1,000,000' into int","int('1,000,000'.replace(',', ''))"
combine dataframe `df1` and dataframe `df2` by index number,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer')"
check if all boolean values in a python dictionary `dict` are true,all(dict.values())
use regex pattern '^12(?=.{4}$)' to remove digit 12 if followed by 4 other digits in column `c_contofficeID` of dataframe `df`,"df.c_contofficeID.str.replace('^12(?=.{4}$)', '')"
reverse a list `L`,L[::(-1)]
reverse a list `array`,reversed(array)
reverse a list `L`,L.reverse()
reverse a list `array`,list(reversed(array))
get first element of each tuple in list `A`,[tup[0] for tup in A]
replace character 'a' with character 'e' and character 's' with character '3' in file `contents`,"newcontents = contents.replace('a', 'e').replace('s', '3')"
serialise SqlAlchemy RowProxy object `row` to a json object,json.dumps([dict(list(row.items())) for row in rs])
get file '~/foo.ini',config_file = os.path.expanduser('~/foo.ini')
get multiple parameters with same name from a url in pylons,request.params.getall('c')
Convert array `x` into a correlation matrix,np.corrcoef(x)
"Find the greatest number in set `(1, 2, 3)`","print(max(1, 2, 3))"
Retrieve parameter 'var_name' from a GET request.,self.request.get('var_name')
"Add 100 to each element of column ""x"" in dataframe `a`","a['x'].apply(lambda x, y: x + y, args=(100,))"
Django get first 10 records of model `User` ordered by criteria 'age' of model 'pet',User.objects.order_by('-pet__age')[:10]
"delay for ""5"" seconds",time.sleep(5)
make a 60 seconds time delay,time.sleep(60)
make a 0.1 seconds time delay,sleep(0.1)
make a 60 seconds time delay,time.sleep(60)
make a 0.1 seconds time delay,time.sleep(0.1)
"From a list of strings `my_list`, remove the values that contains numbers.",[x for x in my_list if not any(c.isdigit() for c in x)]
get the middle two characters of a string 'state' in a pandas dataframe `df`,df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])
draw a grid line on every tick of plot `plt`,plt.grid(True)
sort list `lst` based on each element's number of occurrences,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))"
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)]
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')
calculat the difference between each row and the row previous to it in dataframe `data`,data.set_index('Date').diff()
"append values `[3, 4]` to a set `a`","a.update([3, 4])"
set every two-stride far element to -1 starting from second element in array `a`,a[1::2] = -1
"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)
"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')"
Convert a binary value '1633837924' to string,"struct.pack('<I', 1633837924)"
append string `foo` to list `list`,list.append('foo')
insert string `foo` at position `0` of list `list`,"list.insert(0, 'foo')"
convert keys in dictionary `thedict` into case insensitive,theset = set(k.lower() for k in thedict)
pad 'dog' up to a length of 5 characters with 'x',"""""""{s:{c}^{n}}"""""".format(s='dog', n=5, c='x')"
check if type of variable `s` is a string,"isinstance(s, str)"
check if type of a variable `s` is string,"isinstance(s, str)"
Convert list of dictionaries `L` into a flat dictionary,dict(pair for d in L for pair in list(d.items()))
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())}"
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)"
sort a pandas data frame by column `Peak` in ascending and `Weeks` in descending order,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
"run the code contained in string ""print('Hello')""","eval(""print('Hello')"")"
"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}]"
get all possible combination of items from 2-dimensional list `a`,list(itertools.product(*a))
"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()"
"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]]"
remove Nan values from array `x`,x = x[numpy.logical_not(numpy.isnan(x))]
remove first directory from path '/First/Second/Third/Fourth/Fifth',os.path.join(*x.split(os.path.sep)[2:])
Replace `;` with `:` in a string `line`,"line = line.replace(';', ':')"
call bash command 'tar c my_dir | md5sum' with pipe,"subprocess.call('tar c my_dir | md5sum', shell=True)"
Convert a hex string `437c2123 ` according to ascii value.,"""""""437c2123"""""".decode('hex')"
Get a list of all fields in class `User` that are marked `required`,"[k for k, v in User._fields.items() if v.required]"
"remove column by index `[:, 0:2]` in dataframe `df`","df = df.ix[:, 0:2]"
change a string of integers `x` separated by spaces to a list of int,"x = map(int, x.split())"
convert a string of integers `x` separated by spaces to a list of integers,x = [int(i) for i in x.split()]
"find element by css selector ""input[onclick*='1 Bedroom Deluxe']""","driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")"
display a pdf file that has been downloaded as `my_pdf.pdf`,webbrowser.open('file:///my_pdf.pdf')
replace backslashes in string `result` with empty string '',"result = result.replace('\\', '')"
remove backslashes from string `result`,"result.replace('\\', '')"
"replace value '-' in any column of pandas dataframe to ""NaN""","df.replace('-', 'NaN')"
convert datetime object to date object in python,datetime.datetime.now().date()
get all sub-elements of an element `a` in an elementtree,[elem.tag for elem in a.iter()]
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]
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')"
check if all values of a dictionary `your_dict` are zero `0`,all(value == 0 for value in list(your_dict.values()))
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')"
call `doSomething()` in a try-except without handling the exception,"try:
doSomething()
except:
pass"
call `doSomething()` in a try-except without handling the exception,"try:
doSomething()
except Exception:
pass"
get a sum of 4d array `M`,M.sum(axis=0).sum(axis=0)
Convert a datetime object `dt` to microtime,time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
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)]
sort a list of lists `L` by index 2 of the inner list,"sorted(L, key=itemgetter(2))"
sort a list of lists `l` by index 2 of the inner list,l.sort(key=(lambda x: x[2]))
sort list `l` by index 2 of the item,"sorted(l, key=(lambda x: x[2]))"
"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))"