idx
int64
0
2.38k
question
stringlengths
5
184
target
stringlengths
5
213
100
Clicking a link using selenium using python
driver . find_element_by_xpath ( 'xpath' ) . click ( )
101
count unique index values in column 'A' in pandas dataframe `ex`
ex . groupby ( level = 'A' ) . agg ( lambda x : x . index . get_level_values ( 1 ) . nunique ( ) )
102
Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries
pd . concat ( map ( pd . DataFrame , iter ( d . values ( ) ) ) , keys = list ( d . keys ( ) ) ) . stack ( ) . unstack ( 0 )
103
find out the number of non-matched elements at the same index of list `a` and list `b`
sum ( 1 for i , j in zip ( a , b ) if i != j )
104
make all keys lowercase in dictionary `d`
d = { ( a . lower ( ) , b ) : v for ( a , b ) , v in list ( d . items ( ) ) }
105
sort list `list_` based on first element of each tuple and by the length of the second element of each tuple
list_ . sort ( key = lambda x : [ x [ 0 ] , len ( x [ 1 ] ) , x [ 1 ] ] )
106
trim whitespace in string `s`
s . strip ( )
107
trim whitespace (including tabs) in `s` on the left side
s = s . lstrip ( )
108
trim whitespace (including tabs) in `s` on the right side
s = s . rstrip ( )
109
trim characters ' \t\n\r' in `s`
s = s . strip ( ' \t\n\r' )
110
trim whitespaces (including tabs) in string `s`
print ( re . sub ( '[\\s+]' , '' , s ) )
111
In Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']
Task . objects . exclude ( prerequisites__status__in = [ 'A' , 'P' , 'F' ] )
112
Change background color in Tkinter
root . configure ( background = 'black' )
113
convert dict `result` to numpy structured array
numpy . array ( [ ( key , val ) for key , val in result . items ( ) ] , dtype )
114
Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y'
pd . concat ( [ df_1 , df_2 . sort_values ( 'y' ) ] )
115
replace the last occurence of an expression '</div>' with '</bad>' in a string `s`
re . sub ( '(.*)</div>' , '\\1</bad>' , s )
116
get the maximum of 'salary' and 'bonus' values in a dictionary
print ( max ( d , key = lambda x : ( d [ x ] [ 'salary' ] , d [ x ] [ 'bonus' ] ) ) )
117
Filter Django objects by `author` with ids `1` and `2`
Book . objects . filter ( author__id = 1 ) . filter ( author__id = 2 )
118
split string 'fooxyzbar' based on case-insensitive matching using string 'XYZ'
re . compile ( 'XYZ' , re . IGNORECASE ) . split ( 'fooxyzbar' )
119
get list of sums of neighboring integers in string `example`
[ sum ( map ( int , s ) ) for s in example . split ( ) ]
120
Get all the keys from dictionary `y` whose value is `1`
[ i for i in y if y [ i ] == 1 ]
121
converting byte string `c` in unicode string
c . decode ( 'unicode_escape' )
122
unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`
pd . melt ( x , id_vars = [ 'farm' , 'fruit' ] , var_name = 'year' , value_name = 'value' )
123
add key "item3" and value "3" to dictionary `default_data `
default_data [ 'item3' ] = 3
124
add key "item3" and value "3" to dictionary `default_data `
default_data . update ( { 'item3' : 3 , } )
125
add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`
default_data . update ( { 'item4' : 4 , 'item5' : 5 , } )
126
Get the first and last 3 elements of list `l`
l [ : 3 ] + l [ - 3 : ]
127
reset index to default in dataframe `df`
df = df . reset_index ( drop = True )
128
For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.
[ a [ x ] . append ( b [ x ] ) for x in range ( 3 ) ]
129
get canonical path of the filename `path`
os . path . realpath ( path )
130
check if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`
set ( L [ 0 ] . f . items ( ) ) . issubset ( set ( a3 . f . items ( ) ) )
131
find all the indexes in a Numpy 2D array where the value is 1
zip ( * np . where ( a == 1 ) )
132
How to find the index of a value in 2d array in Python?
np . where ( a == 1 )
133
Collapse hierarchical column index to level 0 in dataframe `df`
df . columns = df . columns . get_level_values ( 0 )
134
create a matrix from a list `[1, 2, 3]`
x = scipy . matrix ( [ 1 , 2 , 3 ] ) . transpose ( )
135
add character '@' after word 'get' in string `text`
text = re . sub ( '(\\bget\\b)' , '\\1@' , text )
136
get a numpy array that contains the element wise minimum of three 3x1 arrays
np . array ( [ np . arange ( 3 ) , np . arange ( 2 , - 1 , - 1 ) , np . ones ( ( 3 , ) ) ] ) . min ( axis = 0 )
137
add a column 'new_col' to dataframe `df` for index in range
df [ 'new_col' ] = list ( range ( 1 , len ( df ) + 1 ) )
138
set environment variable 'DEBUSSY' equal to 1
os . environ [ 'DEBUSSY' ] = '1'
139
Get a environment variable `DEBUSSY`
print ( os . environ [ 'DEBUSSY' ] )
140
set environment variable 'DEBUSSY' to '1'
os . environ [ 'DEBUSSY' ] = '1'
141
update dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`
b . update ( d )
142
get all the values in column `b` from pandas data frame `df`
df [ 'b' ]
143
make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)
ebar = plt . errorbar ( x , y , yerr = err , ecolor = 'y' )
144
find all files with extension '.c' in directory `folder`
results += [ each for each in os . listdir ( folder ) if each . endswith ( '.c' ) ]
145
add unicode string '1' to UTF-8 decoded string '\xc2\xa3'
print ( '\xc2\xa3' . decode ( 'utf8' ) + '1' )
146
lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\1'
re . sub ( '(?<=[a-z])([A-Z])' , '-\\1' , s ) . lower ( )
147
Setting stacksize in a python script
os . system ( 'ulimit -s unlimited; some_executable' )
148
format a string `num` using string formatting
"""{0:.3g}""" . format ( num )
149
append the first element of array `a` to array `a`
numpy . append ( a , a [ 0 ] )
150
return the column for value 38.15 in dataframe `df`
df . ix [ : , ( df . loc [ 0 ] == 38.15 ) ] . columns
151
merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date'
df2 [ 'revenue' ] = df2 . CET . map ( df1 . set_index ( 'date' ) [ 'revenue' ] )
152
load a json data `json_string` into variable `json_data`
json_data = json . loads ( json_string )
153
convert radians 1 to degrees
math . cos ( math . radians ( 1 ) )
154
count the number of integers in list `a`
sum ( isinstance ( x , int ) for x in a )
155
replacing '\u200b' with '*' in a string using regular expressions
'used\u200b' . replace ( '\u200b' , '*' )
156
run function 'SudsMove' simultaneously
threading . Thread ( target = SudsMove ) . start ( )
157
sum of squares values in a list `l`
sum ( i * i for i in l )
158
calculate the sum of the squares of each value in list `l`
sum ( map ( lambda x : x * x , l ) )
159
Create a dictionary `d` from list `iterable`
d = dict ( ( ( key , value ) for ( key , value ) in iterable ) )
160
Create a dictionary `d` from list `iterable`
d = { key : value for ( key , value ) in iterable }
161
Create a dictionary `d` from list of key value pairs `iterable`
d = { k : v for ( k , v ) in iterable }
162
round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places
df . round ( { 'Alabama_exp' : 2 , 'Credit_exp' : 3 } )
163
Make function `WRITEFUNCTION` output nothing in curl `p`
p . setopt ( pycurl . WRITEFUNCTION , lambda x : None )
164
return a random word from a word list 'words'
print ( random . choice ( words ) )
165
Find a max value of the key `count` in a nested dictionary `d`
max ( d , key = lambda x : d [ x ] [ 'count' ] )
166
get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings
[ ( int ( x ) if x else 0 ) for x in data . split ( ',' ) ]
167
split string `s` into a list of strings based on ',' then replace empty strings with zero
""",""" . join ( x or '0' for x in s . split ( ',' ) )
168
regular expression match nothing
re . compile ( '$^' )
169
regular expression syntax for not to match anything
re . compile ( '.\\A|.\\A*|.\\A+' )
170
create a regular expression object with a pattern that will match nothing
re . compile ( 'a^' )
171
drop all columns in dataframe `df` that holds a maximum value bigger than 0
df . columns [ df . max ( ) > 0 ]
172
check if date `yourdatetime` is equal to today's date
yourdatetime . date ( ) == datetime . today ( ) . date ( )
173
print bold text 'Hello'
print ( '\x1b[1m' + 'Hello' )
174
remove 20 symbols in front of '.' in string 'unique12345678901234567890.mkv'
re . sub ( '.{20}(.mkv)' , '\\1' , 'unique12345678901234567890.mkv' )
175
Define a list with string values `['a', 'c', 'b', 'obj']`
[ 'a' , 'c' , 'b' , 'obj' ]
176
substitute multiple whitespace with single whitespace in string `mystring`
""" """ . join ( mystring . split ( ) )
177
print a floating point number 2.345e-67 without any truncation
print ( '{:.100f}' . format ( 2.345e-67 ) )
178
Check if key 'key1' in `dict`
( 'key1' in dict )
179
Check if key 'a' in `d`
( 'a' in d )
180
Check if key 'c' in `d`
( 'c' in d )
181
Check if a given key 'key1' exists in dictionary `dict`
if ( 'key1' in dict ) : pass
182
Check if a given key `key` exists in dictionary `d`
if ( key in d ) : pass
183
create a django query for a list of values `1, 4, 7`
Blog . objects . filter ( pk__in = [ 1 , 4 , 7 ] )
184
read a binary file 'test/test.pdf'
f = open ( 'test/test.pdf' , 'rb' )
185
insert ' ' between every three digit before '.' and replace ',' with '.' in 12345678.46
format ( 12345678.46 , ',' ) . replace ( ',' , ' ' ) . replace ( '.' , ',' )
186
Join pandas data frame `frame_1` and `frame_2` with left join by `county_ID` and right join by `countyid`
pd . merge ( frame_1 , frame_2 , left_on = 'county_ID' , right_on = 'countyid' )
187
calculate ratio of sparsity in a numpy array `a`
np . isnan ( a ) . sum ( ) / np . prod ( a . shape )
188
reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values
sorted ( iter ( cityPopulation . items ( ) ) , key = lambda k_v : k_v [ 1 ] [ 2 ] , reverse = True )
189
Sort dictionary `u` in ascending order based on second elements of its values
sorted ( list ( u . items ( ) ) , key = lambda v : v [ 1 ] )
190
reverse sort dictionary `d` based on its values
sorted ( list ( d . items ( ) ) , key = lambda k_v : k_v [ 1 ] , reverse = True )
191
sorting a defaultdict `d` by value
sorted ( list ( d . items ( ) ) , key = lambda k_v : k_v [ 1 ] )
192
open a file 'bundled-resource.jpg' in the same directory as a python script
f = open ( os . path . join ( __location__ , 'bundled-resource.jpg' ) )
193
open the file 'words.txt' in 'rU' mode
f = open ( 'words.txt' , 'rU' )
194
divide the values with same keys of two dictionary `d1` and `d2`
{ k : ( float ( d2 [ k ] ) / d1 [ k ] ) for k in d2 }
195
divide the value for each key `k` in dict `d2` by the value for the same key `k` in dict `d1`
{ k : ( d2 [ k ] / d1 [ k ] ) for k in list ( d1 . keys ( ) ) & d2 }
196
divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`
dict ( ( k , float ( d2 [ k ] ) / d1 [ k ] ) for k in d2 )
197
write dataframe `df` to csv file `filename` with dates formatted as yearmonthday `%Y%m%d`
df . to_csv ( filename , date_format = '%Y%m%d' )
198
remove a key 'key' from a dictionary `my_dict`
my_dict . pop ( 'key' , None )
199
replace NaN values in array `a` with zeros
b = np . where ( np . isnan ( a ) , 0 , a )