text
stringlengths 4
1.08k
|
|---|
Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`,"pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)"
|
read a text file 'very_Important.txt' into a string variable `str`,"str = open('very_Important.txt', 'r').read()"
|
Return values for column `C` after group by on column `A` and `B` in dataframe `df`,"df.groupby(['A', 'B'])['C'].unique()"
|
read file `fname` line by line into a list `content`,"with open(fname) as f:
|
content = f.readlines()"
|
read file 'filename' line by line into a list `lines`,"with open('filename') as f:
|
lines = f.readlines()"
|
read file 'filename' line by line into a list `lines`,lines = [line.rstrip('\n') for line in open('filename')]
|
convert the dataframe column 'col' from string types to datetime types,df['col'] = pd.to_datetime(df['col'])
|
get a list of the keys in each dictionary in a dictionary of dictionaries `foo`,[k for d in list(foo.values()) for k in d]
|
"get user input using message 'Enter name here: ' and insert it to the first placeholder in string 'Hello, {0}, how do you do?'","print('Hello, {0}, how do you do?'.format(input('Enter name here: ')))"
|
create pandas data frame `df` from txt file `filename.txt` with column `Region Name` and separator `;`,"df = pd.read_csv('filename.txt', sep=';', names=['Region Name'])"
|
get the platform OS name,platform.system()
|
sort list `a` in ascending order based on its elements' float values,"a = sorted(a, key=lambda x: float(x))"
|
finding words in string `s` after keyword 'name',"re.search('name (.*)', s)"
|
Find all records from collection `collection` without extracting mongo id `_id`,"db.collection.find({}, {'_id': False})"
|
Get all the second values from a list of lists `A`,[row[1] for row in A]
|
extract first column from a multi-dimensional array `a`,[row[0] for row in a]
|
"sort list `['10', '3', '2']` in ascending order based on the integer value of its elements","sorted(['10', '3', '2'], key=int)"
|
check if file `filename` is descendant of directory '/the/dir/',"os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'"
|
check if any element of list `substring_list` are in string `string`,any(substring in string for substring in substring_list)
|
construct pandas dataframe from a list of tuples,"df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])"
|
find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's',"re.sub('^((?:(?!cat).)*cat(?:(?!cat).)*)cat', '\\1Bull', s)"
|
find and replace 2nd occurrence of word 'cat' by 'Bull' in a sentence 's',"re.sub('^((.*?cat.*?){1})cat', '\\1Bull', s)"
|
sort list of strings in list `the_list` by integer suffix,"sorted(the_list, key=lambda k: int(k.split('_')[1]))"
|
"sort list of strings `the_list` by integer suffix before ""_""","sorted(the_list, key=lambda x: int(x.split('_')[1]))"
|
make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character,"[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]"
|
Load the url `http://www.google.com` in selenium webdriver `driver`,driver.get('http://www.google.com')
|
"using python's datetime module, get the year that utc-11 is currently in",(datetime.datetime.utcnow() - datetime.timedelta(hours=11)).year
|
"Get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values","Counter([1, 2, 2, 2, 3]) - Counter([1, 2])"
|
remove tags from a string `mystring`,"re.sub('<[^>]*>', '', mystring)"
|
encode string `data` as `hex`,data.encode('hex')
|
filter `Users` by field `userprofile` with level greater than or equal to `0`,User.objects.filter(userprofile__level__gte=0)
|
BeautifulSoup find a tag whose id ends with string 'para',soup.findAll(id=re.compile('para$'))
|
select `div` tags whose `id`s begin with `value_xxx_c_1_f_8_a_`,"soup.select('div[id^=""value_xxx_c_1_f_8_a_""]')"
|
delete an item `thing` in a list `some_list` if it exists,cleaned_list = [x for x in some_list if x is not thing]
|
"print ""Please enter something: "" to console, and read user input to `var`",var = input('Please enter something: ')
|
append 4 to list `foo`,foo.append(4)
|
"append a list [8, 7] to list `foo`","foo.append([8, 7])"
|
insert 77 to index 2 of list `x`,"x.insert(2, 77)"
|
remove white space padding around a saved image `test.png` in matplotlib,"plt.savefig('test.png', bbox_inches='tight')"
|
concatenate lists `listone` and `listtwo`,(listone + listtwo)
|
iterate items in lists `listone` and `listtwo`,"for item in itertools.chain(listone, listtwo):
|
pass"
|
create dataframe `males` containing data of dataframe `df` where column `Gender` is equal to 'Male' and column `Year` is equal to 2014,males = df[(df[Gender] == 'Male') & (df[Year] == 2014)]
|
print backslash,print('\\')
|
replace '-' in pandas dataframe `df` with `np.nan`,"df.replace('-', np.nan)"
|
delete column 'column_name' from dataframe `df`,"df = df.drop('column_name', 1)"
|
"delete 1st, 2nd and 4th columns from dataframe `df`","df.drop(df.columns[[0, 1, 3]], axis=1)"
|
delete a column `column_name` without having to reassign from pandas data frame `df`,"df.drop('column_name', axis=1, inplace=True)"
|
disable abbreviation in argparse,parser = argparse.ArgumentParser(allow_abbrev=False)
|
extract dictionary values by key 'Feature3' from data frame `df`,feature3 = [d.get('Feature3') for d in df.dic]
|
get data of column 'A' and column 'B' in dataframe `df` where column 'A' is equal to 'foo',"df.loc[gb.groups['foo'], ('A', 'B')]"
|
"print '[1, 2, 3]'","print('[%s, %s, %s]' % (1, 2, 3))"
|
Display `1 2 3` as a list of string,"print('[{0}, {1}, {2}]'.format(1, 2, 3))"
|
get values from a dictionary `my_dict` whose key contains the string `Date`,"[v for k, v in list(my_dict.items()) if 'Date' in k]"
|
drop a single subcolumn 'a' in column 'col1' from a dataframe `df`,"df.drop(('col1', 'a'), axis=1)"
|
"dropping all columns named 'a' from a multiindex 'df', across all level.","df.drop('a', level=1, axis=1)"
|
build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter,{_key: _value(_key) for _key in _container}
|
click on the text button 'section-select-all' using selenium python,browser.find_element_by_class_name('section-select-all').click()
|
"combine two dictionaries `d ` and `d1`, concatenate string values with identical `keys`","dict((k, d.get(k, '') + d1.get(k, '')) for k in keys)"
|
generate unique equal hash for equal dictionaries `a` and `b`,hash(pformat(a)) == hash(pformat(b))
|
"convert nested list of lists `[['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]` into a list of tuples","list(map(tuple, [['tom', 'cat'], ['jerry', 'mouse'], ['spark', 'dog']]))"
|
"sum the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df`","df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()"
|
change string `s` to upper case,s.upper()
|
split a string `s` by ';' and convert to a dictionary,dict(item.split('=') for item in s.split(';'))
|
"Add header `('Cookie', 'cookiename=cookie value')` to mechanize browser `br`","br.addheaders = [('Cookie', 'cookiename=cookie value')]"
|
set data in column 'value' of dataframe `df` equal to first element of each list,df['value'] = df['value'].str[0]
|
get element at index 0 of each list in column 'value' of dataframe `df`,df['value'] = df['value'].str.get(0)
|
remove square bracket '[]' from pandas dataframe `df` column 'value',df['value'] = df['value'].str.strip('[]')
|
Get a string with string formatting from dictionary `d`,""""""", """""".join(['{}_{}'.format(k, v) for k, v in d.items()])"
|
"Sum of sums of each list, in a list of lists named 'lists'.",sum(sum(x) for x in lists)
|
"Check whether a numpy array `a` contains a given row `[1, 2]`","any(np.equal(a, [1, 2]).all(1))"
|
check if all elements in list `mylist` are the same,len(set(mylist)) == 1
|
split a string `s` at line breaks `\r\n`,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]"
|
sort a dictionary `a` by values that are list type,"t = sorted(list(a.items()), key=lambda x: x[1])"
|
insert string `string1` after each character of `string2`,"string2.replace('', string1)[len(string1):-len(string1)]"
|
getting every possible combination of two elements in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))"
|
get a utf-8 string literal representation of byte string `x`,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')"
|
check if `x` is an integer,"isinstance(x, int)"
|
check if `x` is an integer,(type(x) == int)
|
play the wav file 'sound.wav',"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)"
|
create a list containing the `n` next values of generator `it`,[next(it) for _ in range(n)]
|
get list of n next values of a generator `it`,"list(itertools.islice(it, 0, n, 1))"
|
compare two lists in python `a` and `b` and return matches,set(a).intersection(b)
|
convert list `data` into a string of its elements,"print(''.join(map(str, data)))"
|
match regex pattern '\\$[0-9]+[^\\$]*$' on string '$1 off delicious $5 ham.',"re.match('\\$[0-9]+[^\\$]*$', '$1 off delicious $5 ham.')"
|
import a nested module `c.py` within `b` within `a` with importlib,"importlib.import_module('.c', 'a.b')"
|
import a module 'a.b.c' with importlib.import_module in python 2,importlib.import_module('a.b.c')
|
Convert array `a` to numpy array,a = np.array(a)
|
Find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`,"soup.find_all('div', class_=re.compile('comment-'))"
|
a sequence of empty lists of length `n`,[[] for _ in range(n)]
|
create dictionary from list of variables 'foo' and 'bar' already defined,"dict((k, globals()[k]) for k in ('foo', 'bar'))"
|
get two random records from model 'MyModel' in Django,MyModel.objects.order_by('?')[:2]
|
Print a dictionary `{'user': {'name': 'Markus'}}` with string formatting,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
|
create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key,list_dict = {t[0]: t for t in tuple_list}
|
Generate a random integer between 0 and 9,"randint(0, 9)"
|
Generate a random integer between `a` and `b`,"random.randint(a, b)"
|
Generate random integers between 0 and 9,"print((random.randint(0, 9)))"
|
reverse a string `a` by 2 characters at a time,""""""""""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.