text
stringlengths 4
1.08k
|
|---|
Change data type of data in column 'grade' of dataframe `data_df` into float and then to int,data_df['grade'] = data_df['grade'].astype(float).astype(int)
|
Find the list in a list of lists `alkaline_earth_values` with the max value of the second element.,"max(alkaline_earth_values, key=lambda x: x[1])"
|
remove leading and trailing zeros in the string 'your_Strip',your_string.strip('0')
|
generate a list of all unique pairs of integers in `range(9)`,"list(permutations(list(range(9)), 2))"
|
create a regular expression that matches the pattern '^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)' over multiple lines of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)"
|
"regular expression ""^(.+)\\n((?:\\n.+)+)"" matching a multiline block of text","re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)"
|
Run 'test2.py' file with python location 'path/to/python' and arguments 'neededArgumetGoHere' as a subprocess,"call(['path/to/python', 'test2.py', 'neededArgumetGoHere'])"
|
sort a multidimensional list `a` by second and third column,"a.sort(key=operator.itemgetter(2, 3))"
|
Add a tuple with value `another_choice` to a tuple `my_choices`,"final_choices = ((another_choice,) + my_choices)"
|
Add a tuple with value `another_choice` to a tuple `my_choices`,"final_choices = ((another_choice,) + my_choices)"
|
find the current directory,os.getcwd()
|
find the current directory,os.path.realpath(__file__)
|
get the directory name of `path`,os.path.dirname(path)
|
get the canonical path of file `path`,os.path.realpath(path)
|
Find name of current directory,dir_path = os.path.dirname(os.path.realpath(__file__))
|
Find current directory,cwd = os.getcwd()
|
Find the full path of current directory,full_path = os.path.realpath(__file__)
|
sort array `arr` in ascending order by values of the 3rd column,"arr[arr[:, (2)].argsort()]"
|
sort rows of numpy matrix `arr` in ascending order according to all column values,"numpy.sort(arr, axis=0)"
|
"split string 'a b.c' on space "" "" and dot character "".""","re.split('[ .]', 'a b.c')"
|
copy the content of file 'file.txt' to file 'file2.txt',"shutil.copy('file.txt', 'file2.txt')"
|
generate random upper-case ascii string of 12 characters length,print(''.join(choice(ascii_uppercase) for i in range(12)))
|
merge the elements in a list `lst` sequentially,"[''.join(seq) for seq in zip(lst, lst[1:])]"
|
rename column 'gdp' in dataframe `data` to 'log(gdp)',"data.rename(columns={'gdp': 'log(gdp)'}, inplace=True)"
|
convert a beautiful soup html `soup` to text,print(soup.get_text())
|
Sort list `li` in descending order based on the second element of each list inside list`li`,"sorted(li, key=operator.itemgetter(1), reverse=True)"
|
replace value 0 with 'Female' and value 1 with 'Male' in column 'sex' of dataframe `data`,"data['sex'].replace([0, 1], ['Female', 'Male'], inplace=True)"
|
"split string 'Words, words, words.' on punctuation","re.split('\\W+', 'Words, words, words.')"
|
"Extract first two substrings in string `phrase` that end in `.`, `?` or `!`","re.match('(.*?[.?!](?:\\s+.*?[.?!]){0,1})', phrase).group(1)"
|
split string `s` into strings of repeating elements,"print([a for a, b in re.findall('((\\w)\\2*)', s)])"
|
Create new string with unique characters from `s` seperated by ' ',print(' '.join(OrderedDict.fromkeys(s)))
|
create a set from string `s` to remove duplicate characters,print(' '.join(set(s)))
|
list folders in zip file 'file' that ends with '/',[x for x in file.namelist() if x.endswith('/')]
|
find the count of a word 'Hello' in a string `input_string`,input_string.count('Hello')
|
"reduce the first element of list of strings `data` to a string, separated by '.'",print('.'.join([item[0] for item in data]))
|
Move the cursor of file pointer `fh1` at the end of the file.,fh1.seek(2)
|
"convert a flat list into a list of tuples of every two items in the list, in order","print(zip(my_list[0::2], my_list[1::2]))"
|
group a list of ints into a list of tuples of each 2 elements,"my_new_list = zip(my_list[0::2], my_list[1::2])"
|
set the default encoding to 'utf-8',sys.setdefaultencoding('utf8')
|
Formate current date and time to a string using pattern '%Y-%m-%d %H:%M:%S',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
retrieve arabic texts from string `my_string`,"print(re.findall('[\\u0600-\\u06FF]+', my_string))"
|
group dataframe `df` based on minute interval,df.groupby(df.index.map(lambda t: t.minute))
|
access value associated with key 'American' of key 'Apple' from dictionary `dict`,dict['Apple']['American']
|
"remove all null values from columns 'three', 'four' and 'five' of dataframe `df2`","df2.dropna(subset=['three', 'four', 'five'], how='all')"
|
insert a list `k` at the front of list `a`,"a.insert(0, k)"
|
insert elements of list `k` into list `a` at position `n`,a = a[:n] + k + a[n:]
|
calculate the mean of the nonzero values' indices of dataframe `df`,np.flatnonzero(x).mean()
|
get date from dataframe `df` column 'dates' to column 'just_date',df['just_date'] = df['dates'].dt.date
|
remove elements in list `b` from list `a`,[x for x in a if x not in b]
|
join elements of each tuple in list `a` into one string,[''.join(x) for x in a]
|
join items of each tuple in list of tuples `a` into a list of strings,"list(map(''.join, a))"
|
match blank lines in `s` with regular expressions,"re.split('\n\\s*\n', s)"
|
"merge a list of integers `[1, 2, 3, 4, 5]` into a single integer","from functools import reduce
|
reduce(lambda x, y: 10 * x + y, [1, 2, 3, 4, 5])"
|
Convert float 24322.34 to comma-separated string,"""""""{0:,.2f}"""""".format(24322.34)"
|
pass dictionary items `data` as keyword arguments in function `my_function`,my_function(**data)
|
get line count of file 'myfile.txt',sum((1 for line in open('myfile.txt')))
|
round 1123.456789 to be an integer,"print(round(1123.456789, -1))"
|
sort list `X` based on values from another list `Y`,"[x for y, x in sorted(zip(Y, X))]"
|
sorting list 'X' based on values from another list 'Y',"[x for y, x in sorted(zip(Y, X))]"
|
get equivalent week number from a date `2010/6/16` using isocalendar,"datetime.date(2010, 6, 16).isocalendar()[1]"
|
"select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`","df.iloc[:, (np.r_[1:10, (15), (17), 50:100])]"
|
apply two different aggregating functions `mean` and `sum` to the same column `dummy` in pandas data frame `df`,"df.groupby('dummy').agg({'returns': [np.mean, np.sum]})"
|
convert string `s` to lowercase,s.lower()
|
convert utf-8 string `s` to lowercase,s.decode('utf-8').lower()
|
handle the `urlfetch_errors ` exception for imaplib request to url `url`,"urlfetch.fetch(url, deadline=10 * 60)"
|
output first 100 characters in a string `my_string`,print(my_string[0:100])
|
make matplotlib plot legend put marker in legend only once,legend(numpoints=1)
|
get set intersection between dictionaries `d1` and `d2`,"dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())"
|
convert csv file 'test.csv' into two-dimensional matrix,"numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)"
|
filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`,"Sample.objects.filter(date__range=['2011-01-01', '2011-01-31'])"
|
filter objects month wise in django model `Sample` for year `2011`,"Sample.objects.filter(date__year='2011', date__month='01')"
|
"create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'","d['dict3'] = {'spam': 5, 'ham': 6}"
|
apply `numpy.linalg.norm` to each row of a matrix `a`,"numpy.apply_along_axis(numpy.linalg.norm, 1, a)"
|
merge dictionaries form array `dicts` in a single expression,"dict((k, v) for d in dicts for k, v in list(d.items()))"
|
Convert escaped utf string to utf string in `your string`,print('your string'.decode('string_escape'))
|
"counting the number of true booleans in a python list `[True, True, False, False, False, True]`","sum([True, True, False, False, False, True])"
|
"set the size of figure `fig` in inches to width height of `w`, `h`","fig.set_size_inches(w, h, forward=True)"
|
format string with dict `{'5': 'you'}` with integer keys,'hello there %(5)s' % {'5': 'you'}
|
"Convert a string of numbers `example_string` separated by `,` into a list of integers","map(int, example_string.split(','))"
|
Convert a string of numbers 'example_string' separated by comma into a list of numbers,"[int(s) for s in example_string.split(',')]"
|
Flatten list `x`,x = [i[0] for i in x]
|
convert list `x` into a flat list,"y = map(operator.itemgetter(0), x)"
|
get a list `y` of the first element of every tuple in list `x`,y = [i[0] for i in x]
|
extract all the values of a specific key named 'values' from a list of dictionaries,results = [item['value'] for item in test_data]
|
get current datetime in ISO format,datetime.datetime.now().isoformat()
|
get UTC datetime in ISO format,datetime.datetime.utcnow().isoformat()
|
Merge all columns in dataframe `df` into one column,"df.apply(' '.join, axis=0)"
|
pandas subtract a row from dataframe `df2` from dataframe `df`,"pd.DataFrame(df.values - df2.values, columns=df.columns)"
|
read file 'myfile.txt' using universal newline mode 'U',"print(open('myfile.txt', 'U').read())"
|
print line `line` from text file with 'utf-16-le' format,print(line.decode('utf-16-le').split())
|
open a text file `data.txt` in io module with encoding `utf-16-le`,"file = io.open('data.txt', 'r', encoding='utf-16-le')"
|
Join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes,"s1 = pd.merge(df1, df2, how='inner', on=['user_id'])"
|
check if string `foo` is UTF-8 encoded,foo.decode('utf8').encode('utf8')
|
get the dimensions of numpy array `a`,a.shape
|
get the dimensions of numpy array `a`,N.shape(a)
|
get the dimensions of array `a`,N.shape(a)
|
get the dimensions of numpy array `a`,a.shape
|
get the indices of tuples in list of tuples `L` where the first value is 53,"[i for i, v in enumerate(L) if v[0] == 53]"
|
convert string of bytes `y\xcc\xa6\xbb` into an int,"struct.unpack('<L', 'y\xcc\xa6\xbb')[0]"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.