prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
---|---|
ert a list `k` at the front of list `a` | a.insert(0, k) |
ert elements of list `k` into list `a` at position `n` | a = a[:n] + k + a[n:] |
alculate 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 |
emove 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 string | list(map(''.join, a)) |
h blank lines in `s` with regular expressio | re.split('\n\\s*\n', s) |
erge 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 commaseparated 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'))) |
get line count of file `filename` | def bufcount(filename):
f = open(filename)
lines = 0
buf_size = (1024 * 1024)
read_f = f.read
buf = read_f(buf_size)
while buf:
lines += buf.count('\n')
buf = read_f(buf_size)
return lines |
d 1123.456789 to be an integer | print(round(1123.456789, -1)) |
list `X` based on values from another list `Y` | [x for y, x in sorted(zip(Y, X))] |
g 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] |
elect multiple ranges of columns 110, 15, 17, and 50100 in pandas dataframe `df` | df.iloc[:, (np.r_[1:10, (15), (17), 50:100])] |
pply 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]}) |
vert string `s` to lowercase | s.lower() |
vert utf8 string `s` to lowercase | s.decode('utf-8').lower() |
w to download a file via FTP with Python ftplib | ftp.retrbinary('RETR %s' % filename, file.write) |
handle the `urlfetch_errors ` exception for imaplib request to url `url` | urlfetch.fetch(url, deadline=10 * 60) |
put first 100 characters in a string `my_string` | print(my_string[0:100]) |
ke 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()) |
vert csv file 'test.csv' into twodimensional matrix | numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1) |
filter the objects in django model 'Sample' between date range `20110101` and `20110131` | 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') |
eate a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3' | d['dict3'] = {'spam': 5, 'ham': 6} |
pply `numpy.linalg.norm` to each row of a matrix `a` | numpy.apply_along_axis(numpy.linalg.norm, 1, a) |
erge dictionaries form array `dicts` in a single expressio | 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')) |
g the number of true booleans in a python list `[True, True, False, False, False, True]` | sum([True, True, False, False, False, True]) |
et 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 key | 'hello there %(5)s' % {'5': 'you'} |
Convert a string of numbers `example_string` separated by `,` into a list of integer | map(int, example_string.split(',')) |
Convert a string of numbers 'example_string' separated by comma into a list of number | [int(s) for s in example_string.split(',')] |
Flatten list `x` | x = [i[0] for i in x] |
vert list `x` into a flat l | 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 dictionarie | results = [item['value'] for item in test_data] |
get current datetime in ISO form | datetime.datetime.now().isoformat() |
get UTC datetime in ISO form | datetime.datetime.utcnow().isoformat() |
Merge all columns in dataframe `df` into one colum | df.apply(' '.join, axis=0) |
pandas subtract a row from dataframe `df2` from dataframe `df` | pd.DataFrame(df.values - df2.values, columns=df.columns) |
ead file 'myfile.txt' using universal newline mode 'U' | print(open('myfile.txt', 'U').read()) |
print line `line` from text file with 'utf16le' form | print(line.decode('utf-16-le').split()) |
pen a text file `data.txt` in io module with encoding `utf16le` | 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 dataframe | s1 = pd.merge(df1, df2, how='inner', on=['user_id']) |
heck if string `foo` is UTF8 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] |
vert string of bytes `y\xcc\xa6\xbb` into an | struct.unpack('<L', 'y\xcc\xa6\xbb')[0] |
get the first row, second column; second row, first column, and first row third column values of numpy array `arr` | arr[[0, 1, 1], [1, 0, 2]] |
eate a list with permutations of string 'abcd' | list(powerset('abcd')) |
Convert string to boolean from defined set of string | s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] |
eplace special characters in url 'http://spam.com/go/' using the '%xx' escape | urllib.parse.quote('http://spam.com/go/') |
Save plot `plt` as svg file 'test.svg' | plt.savefig('test.svg') |
he number of elements in array `myArray` | len(myArray) |
ert directory './path/to/your/modules/' to current directory | sys.path.insert(0, './path/to/your/modules/') |
w to plot with xaxis at the top of the figure? | ax.xaxis.set_ticks_position('top') |
ert records in bulk from table1 of master DB to table1 of sqlite3 `cursor` objec | cursor.execute('INSERT OR REPLACE INTO master.table1 SELECT * FROM table1') |
Match regex '[azAZ][\\w]*\\Z' on string 'A\n' | re.match('[a-zA-Z][\\w-]*\\Z', 'A\n') |
h regex '[azAZ][\\w]*$' on string '!A_B' | re.match('[a-zA-Z][\\w-]*$', '!A_B') |
Convert hex string deadbeef to integer | int('deadbeef', 16) |
Convert hex string a to integer | int('a', 16) |
Convert hex string 0xa to integer | int('0xa', 16) |
Convert hex string `s` to integer | int(s, 16) |
Convert hex string `hexString` to | int(hexString, 16) |
print variable `value ` without space | print('Value is "' + str(value) + '"') |
Print a string `value` with string formatting | print('Value is "{}"'.format(value)) |
Jinja join elements of array `tags` with space string ' ' | {{tags | join(' ')}} |
get a list of locally installed Python module | help('modules') |
Get only first element in each of the innermost of the multidimensional list `listD` | [[[x[0]] for x in listD[i]] for i in range(len(listD))] |
Sort a string `s` in lexicographic order | sorted(s, key=str.upper) |
g `s` in lexicographic order | sorted(sorted(s), key=str.upper) |
get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters fir | sorted(s, key=str.lower) |
find all the rows in Dataframe 'df2' that are also present in Dataframe 'df1', for the columns 'A', 'B', 'C' and 'D'. | pd.merge(df1, df2, on=['A', 'B', 'C', 'D'], how='inner') |
Reverse keyvalue pairs in a dictionary `map` | dict((v, k) for k, v in map.items()) |
decode unicode string `s` into a readable unicode literal | s.decode('unicode_escape') |
vert list of strings `str_list` into list of integer | [int(i) for i in str_list] |
vert a list with string `['1', '2', '3']` into list with integer | map(int, ['1', '2', '3']) |
vert list with str into list with | list(map(int, ['1', '2', '3'])) |
find all anchor tags in html `soup` whose url begins with `http://www.iwashere.com` | soup.find_all('a', href=re.compile('http://www\\.iwashere\\.com/')) |
find all anchors with a hyperlink that matches the pattern '^(?!(?:[azAZ][azAZ09+.]*:|//))' | soup.find_all('a', href=re.compile('^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))')) |
execute a jar file 'Blender.jar' using subproce | subprocess.call(['java', '-jar', 'Blender.jar']) |
ert row into mysql database with column 'column1' set to the value `value` | cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,)) |
emove a substring .com from the end of string `url` | if url.endswith('.com'):
url = url[:(-4)] |
emove a substring .com from the end of string `url` | url = re.sub('\\.com$', '', url) |
emove a substring .com from the end of string `url` | print(url.replace('.com', '')) |
emove a substring `suffix` from the end of string `text` | if (not text.endswith(suffix)):
return text
return text[:(len(text) - len(suffix))] |
print each first value from a list of tuples `mytuple` with string formatting | print(', ,'.join([str(i[0]) for i in mytuple])) |
lamping floating number `my_value` to be between `min_value` and `max_value` | max(min(my_value, max_value), min_value) |
plit a unicode string `text` into a list of words and punctuation characters with a regex | re.findall('\\w+|[^\\w\\s]', text, re.UNICODE) |
execute raw sql queue '<sql here>' in database `db` in sqlalchemyflask app | result = db.engine.execute('<sql here>') |
quit program | sys.exit(0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.