text
stringlengths
4
1.08k
Set index equal to field 'TRX_DATE' in dataframe `df`,df = df.set_index(['TRX_DATE'])
List comprehension with an accumulator in range of 10,list(accumulate(list(range(10))))
How to convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')"
convert a date string '2013-1-25' in format '%Y-%m-%d' to different format '%-m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%-m/%d/%y')"
get a dataframe `df2` that contains all the columns of dataframe `df` that do not end in `prefix`,"df2 = df.ix[:, (~df.columns.str.endswith('prefix'))]"
create list `new_list` containing the last 10 elements of list `my_list`,new_list = my_list[-10:]
get the last 10 elements from a list `my_list`,my_list[-10:]
convert matlab engine array `x` to a numpy ndarray,np.array(x._data).reshape(x.size[::-1]).T
select the first row grouped per level 0 of dataframe `df`,"df.groupby(level=0, as_index=False).nth(0)"
concatenate sequence of numpy arrays `LIST` into a one dimensional array along the first axis,"numpy.concatenate(LIST, axis=0)"
"convert and escape string ""\\xc3\\x85あ"" to UTF-8 code","""""""\\xc3\\x85あ"""""".encode('utf-8').decode('unicode_escape')"
interleave the elements of two lists `a` and `b`,"[j for i in zip(a, b) for j in i]"
merge two lists `a` and `b` into a single list,"[j for i in zip(a, b) for j in i]"
delete all occureces of `8` in each string `s` in list `lst`,"print([s.replace('8', '') for s in lst])"
"Split string `Hello` into a string of letters seperated by `,`",""""""","""""".join('Hello')"
"in Django, select 100 random records from the database `Content.objects`",Content.objects.all().order_by('?')[:100]
create a NumPy array containing elements of array `A` as pointed to by index in array `B`,"A[np.arange(A.shape[0])[:, (None)], B]"
pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index,"df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)"
match zero-or-more instances of lower case alphabet characters in a string `f233op `,"re.findall('([a-z]*)', 'f233op')"
match zero-or-more instances of lower case alphabet characters in a string `f233op `,"re.findall('([a-z])*', 'f233op')"
split string 'happy_hats_for_cats' using string '_for_',"re.split('_for_', 'happy_hats_for_cats')"
"Split string 'sad_pandas_and_happy_cats_for_people' based on string 'and', 'or' or 'for'","re.split('_(?:for|or|and)_', 'sad_pandas_and_happy_cats_for_people')"
Split a string `l` by multiple words `for` or `or` or `and`,"[re.split('_(?:f?or|and)_', s) for s in l]"
zip keys with individual values in lists `k` and `v`,"[dict(zip(k, x)) for x in v]"
Sort a list 'lst' in descending order.,"sorted(lst, reverse=True)"
"sort array `order_array` based on column 'year', 'month' and 'day'","order_array.sort(order=['year', 'month', 'day'])"
"Sort a structured numpy array 'df' on multiple columns 'year', 'month' and 'day'.","df.sort(['year', 'month', 'day'])"
check if elements in list `my_list` are coherent in order,"return my_list == list(range(my_list[0], my_list[-1] + 1))"
group rows of pandas dataframe `df` with same 'id',df.groupby('id').agg(lambda x: x.tolist())
encode `u'X\xc3\xbcY\xc3\x9f'` as unicode and decode with utf-8,'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8')
parse string `a` to float,float(a)
check if object `a` has property 'property',"if hasattr(a, 'property'):
pass"
check if object `a` has property 'property',"if hasattr(a, 'property'):
pass"
get the value of attribute 'property' of object `a` with default value 'default value',"getattr(a, 'property', 'default value')"
delete every 8th column in a numpy array 'a'.,"np.delete(a, list(range(0, a.shape[1], 8)), axis=1)"
convert `ms` milliseconds to a datetime object,datetime.datetime.fromtimestamp(ms / 1000.0)
find the magnitude (length) squared of a vector `vf` field,"np.einsum('...j,...j->...', vf, vf)"
request http url `url`,r = requests.get(url)
request http url `url` with parameters `payload`,"r = requests.get(url, params=payload)"
post request url `url` with parameters `payload`,"r = requests.post(url, data=payload)"
make an HTTP post request with data `post_data`,"post_response = requests.post(url='http://httpbin.org/post', json=post_data)"
django jinja slice list `mylist` by '3:8',{{(mylist | slice): '3:8'}}
create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet',"df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')"
get the largest index of the last occurrence of characters '([{' in string `test_string`,max(test_string.rfind(i) for i in '([{')
print 'here is your checkmark: ' plus unicode character u'\u2713',print('here is your checkmark: ' + '\u2713')
print unicode characters in a string `\u0420\u043e\u0441\u0441\u0438\u044f`,print('\u0420\u043e\u0441\u0441\u0438\u044f')
pads string '5' on the left with 1 zero,print('{0}'.format('5'.zfill(2)))
Remove duplicates elements from list `sequences` and sort it in ascending order,sorted(set(itertools.chain.from_iterable(sequences)))
pandas dataframe `df` column 'a' to list,df['a'].values.tolist()
Get a list of all values in column `a` in pandas data frame `df`,df['a'].tolist()
escaping quotes in string,"replace('""', '\\""')"
check if all string elements in list `words` are upper-cased,print(all(word[0].isupper() for word in words))
remove items from dictionary `myDict` if the item's value `val` is equal to 42,"myDict = {key: val for key, val in list(myDict.items()) if val != 42}"
Remove all items from a dictionary `myDict` whose values are `42`,"{key: val for key, val in list(myDict.items()) if val != 42}"
Determine the byte length of a utf-8 encoded string `s`,return len(s.encode('utf-8'))
kill a process with id `process.pid`,"os.kill(process.pid, signal.SIGKILL)"
get data of columns with Null values in dataframe `df`,df[pd.isnull(df).any(axis=1)]
"strip everything up to and including the character `&` from url `url`, strip the character `=` from the remaining string and concatenate `.html` to the end","url.split('&')[-1].replace('=', '') + '.html'"
Parse a file `sample.xml` using expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))"
Exit script,sys.exit()
assign value in `group` dynamically to class property `attr`,"setattr(self, attr, group)"
decode url-encoded string `some_string` to its character equivalents,urllib.parse.unquote(urllib.parse.unquote(some_string))
change flask security register url to `/create_account`,app.config['SECURITY_REGISTER_URL'] = '/create_account'
open a file `/home/user/test/wsservice/data.pkl` in binary write mode,"output = open('/home/user/test/wsservice/data.pkl', 'wb')"
remove the last element in list `a`,del a[(-1)]
remove the element in list `a` with index 1,a.pop(1)
remove the last element in list `a`,a.pop()
remove the element in list `a` at index `index`,a.pop(index)
remove the element in list `a` at index `index`,del a[index]
print a celsius symbol on x axis of a plot `ax`,ax.set_xlabel('Temperature (\u2103)')
Print a celsius symbol with matplotlib,ax.set_xlabel('Temperature ($^\\circ$C)')
convert a list of lists `list_of_lists` into a list of strings keeping empty sub-lists as empty string '',[''.join(l) for l in list_of_lists]
get a list of all the duplicate items in dataframe `df` using pandas,"pd.concat(g for _, g in df.groupby('ID') if len(g) > 1)"
Delete third row in a numpy array `x`,"x = numpy.delete(x, 2, axis=1)"
delete first row of array `x`,"x = numpy.delete(x, 0, axis=0)"
merge rows from dataframe `df1` with rows from dataframe `df2` and calculate the mean for rows that have the same value of axis 1,"pd.concat((df1, df2), axis=1).mean(axis=1)"
Get the average values from two numpy arrays `old_set` and `new_set`,"np.mean(np.array([old_set, new_set]), axis=0)"
Matplotlib change marker size to 500,"scatter(x, y, s=500, color='green', marker='h')"
Create new list `result` by splitting each item in list `words`,"result = [item for word in words for item in word.split(',')]"
convert JSON string '2012-05-29T19:30:03.283Z' into a DateTime object using format '%Y-%m-%dT%H:%M:%S.%fZ',"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')"
count `True` values associated with key 'one' in dictionary `tadas`,sum(item['one'] for item in list(tadas.values()))
encode a pdf file `pdf_reference.pdf` with `base64` encoding,"a = open('pdf_reference.pdf', 'rb').read().encode('base64')"
split string `a` using new-line character '\n' as separator,a.rstrip().split('\n')
split a string `a` with new line character,a.split('\n')[:-1]
return http status code 204 from a django view,return HttpResponse(status=204)
check if 7 is in `a`,(7 in a)
check if 'a' is in list `a`,('a' in a)
sort list `results` by keys value 'year',"sorted(results, key=itemgetter('year'))"
get current url in selenium webdriver `browser`,print(browser.current_url)
"split string `str` with delimiter '; ' or delimiter ', '","re.split('; |, ', str)"
un-escaping characters in a string with python,"""""""\\u003Cp\\u003E"""""".decode('unicode-escape')"
convert date string `s` in format pattern '%d/%m/%Y' into a timestamp,"time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())"
convert string '01/12/2011' to an integer timestamp,"int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime('%s'))"
get http header of the key 'your-header-name' in flask,request.headers['your-header-name']
select records of dataframe `df` where the sum of column 'X' for each value in column 'User' is 0,df.groupby('User')['X'].filter(lambda x: x.sum() == 0)
Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0,df.loc[df.groupby('User')['X'].transform(sum) == 0]
Get data from dataframe `df` where column 'X' is equal to 0,df.groupby('User')['X'].transform(sum) == 0
convert pandas group by object to multi-indexed dataframe with indices 'Name' and 'Destination',"df.set_index(['Name', 'Destination'])"