prompt
stringlengths 4
181
| completion
stringlengths 2
232
|
|---|---|
print the number of occurences of not `none` in a list `lst` in Python 2
|
print(len([x for x in lst if x is not None]))
|
lookup dictionary key `key1` in Django template `json`
|
{{json.key1}}
|
emove duplicates from list `myset`
|
mynewlist = list(myset)
|
get unique values from the list `['a', 'b', 'c', 'd']`
|
set(['a', 'b', 'c', 'd'])
|
et size of `figure` to landscape A4 i.e. `11.69, 8.27` inche
|
figure(figsize=(11.69, 8.27))
|
get every thing after last `/`
|
url.rsplit('/', 1)
|
get everything after last slash in a url stored in variable 'url'
|
url.rsplit('/', 1)[-1]
|
pen file '5_1.txt' in directory `direct`
|
x_file = open(os.path.join(direct, '5_1.txt'), 'r')
|
eate a list with the characters of a string `5+6`
|
list('5+6')
|
atenate a list of numpy arrays `input_list` together into a flattened list of value
|
np.concatenate(input_list).ravel().tolist()
|
vert dictionary `dict` into a flat l
|
print([y for x in list(dict.items()) for y in x])
|
Convert a dictionary `dict` into a list with key and values as list items.
|
[y for x in list(dict.items()) for y in x]
|
get a random record from model 'MyModel' using django's orm
|
MyModel.objects.order_by('?').first()
|
hange current working directory to directory 'chapter3'
|
os.chdir('chapter3')
|
hange current working directory
|
os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
|
hange current working directory
|
os.chdir('.\\chapter3')
|
eate a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`
|
dict((key, sum(d[key] for d in dictList)) for key in dictList[0])
|
pandas data frame `df` using values from columns `c1` and `c2` in ascending order
|
df.sort(['c1', 'c2'], ascending=[True, True])
|
Converting string lists `s` to float l
|
floats = [float(x) for x in s.split()]
|
Converting string lists `s` to float l
|
floats = map(float, s.split())
|
et labels `[1, 2, 3, 4, 5]` on axis X in plot `plt`
|
plt.xticks([1, 2, 3, 4, 5])
|
ead line by line from std
|
for line in fileinput.input():
pass
|
ead line by line from std
|
for line in sys.stdin:
pass
|
heck if string `one` exists in the values of dictionary `d`
|
'one' in list(d.values())
|
Check if value 'one' is among the values of dictionary `d`
|
'one' in iter(d.values())
|
all parent class `Instructor` of child class constructor
|
super(Instructor, self).__init__(name, year)
|
eate a dictionary using two lists`x` and `y`
|
dict(zip(x, y))
|
a list of dictionaries `a` by dictionary values in descending order
|
sorted(a, key=lambda i: list(i.values())[0], reverse=True)
|
g a list of dictionary `a` by values in descending order
|
sorted(a, key=dict.values, reverse=True)
|
Use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`
|
df.groupby(level=0).agg(['sum', 'count', 'std'])
|
for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key
|
a.setdefault('somekey', []).append('bob')
|
m values in list of dictionaries `example_list` with key 'gold'
|
sum(item['gold'] for item in example_list)
|
get a sum of all values from key `gold` in a list of dictionary `example_list`
|
sum([item['gold'] for item in example_list])
|
Get all the values in key `gold` summed from a list of dictionary `myLIst`
|
sum(item['gold'] for item in myLIst)
|
writing string 'text to write\n' to file `f`
|
f.write('text to write\n')
|
Write a string `My String` to a file `file` including new line character
|
file.write('My String\n')
|
find consecutive segments from a column 'A' in a pandas data frame 'df'
|
df.reset_index().groupby('A')['index'].apply(np.array)
|
get a relative path of file 'my_file' into variable `fn`
|
fn = os.path.join(os.path.dirname(__file__), 'my_file')
|
etrieve an element from a set `s` without removing
|
e = next(iter(s))
|
execute a command in the command prompt to list directory contents of the c drive `c:\\'
|
os.system('dir c:\\')
|
Make a auto scrolled window to the end of the list in gtk
|
self.treeview.connect('size-allocate', self.treeview_changed)
|
heck if 3 is inside list `[1, 2, 3]`
|
3 in [1, 2, 3]
|
Represent DateTime object '10/05/2012' with format '%d/%m/%Y' into format '%Y%m%d'
|
datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')
|
vert a string literal `s` with values `\\` to raw string literal
|
s = s.replace('\\', '\\\\')
|
get output of script `proc`
|
print(proc.communicate()[0])
|
eate a pandas data frame from list of nested dictionaries `my_list`
|
pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T
|
delete all columns in DataFrame `df` that do not hold a nonzero value in its record
|
df.loc[:, ((df != 0).any(axis=0))]
|
a multidimensional array `a` by column with index 1
|
sorted(a, key=lambda x: x[1])
|
plit string `s` to list conversion by ','
|
[x.strip() for x in s.split(',')]
|
Get a list of items in the list `container` with attribute equal to `value`
|
items = [item for item in container if item.attribute == value]
|
eate a file 'filename' with each tuple in the list `mylist` written to a line
|
open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))
|
Get multiple matched strings using regex pattern `(?:review: )?(http://url.com/(\\d+))\\s?`
|
pattern = re.compile('(?:review: )?(http://url.com/(\\d+))\\s?', re.IGNORECASE)
|
ead 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()
|
ead file `fname` line by line into a list `content`
|
with open(fname) as f:
content = f.readlines()
|
ead file 'filename' line by line into a list `lines`
|
with open('filename') as f:
lines = f.readlines()
|
ead file 'filename' line by line into a list `lines`
|
lines = [line.rstrip('\n') for line in open('filename')]
|
ead file file.txt line by line into a list `array`
|
with open('file.txt', 'r') as ins:
array = []
for line in ins:
array.append(line)
|
vert the dataframe column 'col' from string types to datetime type
|
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: ')))
|
eate 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'])
|
Pandas: How can I use the apply() function for a single column?
|
df['a'] = df['a'].apply(lambda x: x + 1)
|
get the platform OS name
|
platform.system()
|
list `a` in ascending order based on its elements' float value
|
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 multidimensional array `a`
|
[row[0] for row in a]
|
list `['10', '3', '2']` in ascending order based on the integer value of its eleme
|
sorted(['10', '3', '2'], key=int)
|
heck if file `filename` is descendant of directory '/the/dir/'
|
os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'
|
heck if any element of list `substring_list` are in string `string`
|
any(substring in string for substring in substring_list)
|
pandas dataframe from a list of tuple
|
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)
|
list of strings in list `the_list` by integer suffix
|
sorted(the_list, key=lambda k: int(k.split('_')[1]))
|
list of strings `the_list` by integer suffix before _
|
sorted(the_list, key=lambda x: int(x.split('_')[1]))
|
ke 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])]
|
w to group similar items in a list?
|
[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]
|
Load the url `http://www.google.com` in selenium webdriver `driver`
|
driver.get('http://www.google.com')
|
g python's datetime module, get the year that utc11 is currently
|
(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 value
|
Counter([1, 2, 2, 2, 3]) - Counter([1, 2])
|
emove 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$'))
|
elect `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 ex
|
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: ')
|
ppend 4 to list `foo`
|
foo.append(4)
|
ppend a list [8, 7] to list `foo`
|
foo.append([8, 7])
|
ert 77 to index 2 of list `x`
|
x.insert(2, 77)
|
emove white space padding around a saved image `test.png` in matplotlib
|
plt.savefig('test.png', bbox_inches='tight')
|
atenate lists `listone` and `listtwo`
|
(listone + listtwo)
|
erate items in lists `listone` and `listtwo`
|
for item in itertools.chain(listone, listtwo):
pass
|
eate 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('\\')
|
eplace '' 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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.