idx
int64
0
2.38k
question
stringlengths
5
184
target
stringlengths
5
213
600
insert a list `k` at the front of list `a`
a . insert ( 0 , k )
601
insert elements of list `k` into list `a` at position `n`
a = a [ : n ] + k + a [ n : ]
602
calculate the mean of the nonzero values' indices of dataframe `df`
np . flatnonzero ( x ) . mean ( )
603
get date from dataframe `df` column 'dates' to column 'just_date'
df [ 'just_date' ] = df [ 'dates' ] . dt . date
604
remove elements in list `b` from list `a`
[ x for x in a if x not in b ]
605
join elements of each tuple in list `a` into one string
[ '' . join ( x ) for x in a ]
606
join items of each tuple in list of tuples `a` into a list of strings
list ( map ( '' . join , a ) )
607
match blank lines in `s` with regular expressions
re . split ( '\n\\s*\n' , s )
608
merge 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 ] )
609
Convert float 24322.34 to comma-separated string
"""{0:,.2f}""" . format ( 24322.34 )
610
pass dictionary items `data` as keyword arguments in function `my_function`
my_function ( ** data )
611
get line count of file 'myfile.txt'
sum ( ( 1 for line in open ( 'myfile.txt' ) ) )
612
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
613
round 1123.456789 to be an integer
print ( round ( 1123.456789 , - 1 ) )
614
sort list `X` based on values from another list `Y`
[ x for y , x in sorted ( zip ( Y , X ) ) ]
615
sorting list 'X' based on values from another list 'Y'
[ x for y , x in sorted ( zip ( Y , X ) ) ]
616
get equivalent week number from a date `2010/6/16` using isocalendar
datetime . date ( 2010 , 6 , 16 ) . isocalendar ( ) [ 1 ]
617
select multiple ranges of columns 1-10, 15, 17, and 50-100 in pandas dataframe `df`
df . iloc [ : , ( np . r_ [ 1 : 10 , ( 15 ) , ( 17 ) , 50 : 100 ] ) ]
618
apply 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 ] } )
619
convert string `s` to lowercase
s . lower ( )
620
convert utf-8 string `s` to lowercase
s . decode ( 'utf-8' ) . lower ( )
621
How to download a file via FTP with Python ftplib
ftp . retrbinary ( 'RETR %s' % filename , file . write )
622
handle the `urlfetch_errors ` exception for imaplib request to url `url`
urlfetch . fetch ( url , deadline = 10 * 60 )
623
output first 100 characters in a string `my_string`
print ( my_string [ 0 : 100 ] )
624
make matplotlib plot legend put marker in legend only once
legend ( numpoints = 1 )
625
get set intersection between dictionaries `d1` and `d2`
dict ( ( x , set ( y ) & set ( d1 . get ( x , ( ) ) ) ) for x , y in d2 . items ( ) )
626
convert csv file 'test.csv' into two-dimensional matrix
numpy . loadtxt ( open ( 'test.csv' , 'rb' ) , delimiter = ',' , skiprows = 1 )
627
filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`
Sample . objects . filter ( date__range = [ '2011-01-01' , '2011-01-31' ] )
628
filter objects month wise in django model `Sample` for year `2011`
Sample . objects . filter ( date__year = '2011' , date__month = '01' )
629
create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'
d [ 'dict3' ] = { 'spam' : 5 , 'ham' : 6 }
630
apply `numpy.linalg.norm` to each row of a matrix `a`
numpy . apply_along_axis ( numpy . linalg . norm , 1 , a )
631
merge dictionaries form array `dicts` in a single expression
dict ( ( k , v ) for d in dicts for k , v in list ( d . items ( ) ) )
632
Convert escaped utf string to utf string in `your string`
print ( 'your string' . decode ( 'string_escape' ) )
633
counting the number of true booleans in a python list `[True, True, False, False, False, True]`
sum ( [ True , True , False , False , False , True ] )
634
set the size of figure `fig` in inches to width height of `w`, `h`
fig . set_size_inches ( w , h , forward = True )
635
format string with dict `{'5': 'you'}` with integer keys
'hello there %(5)s' % { '5' : 'you' }
636
Convert a string of numbers `example_string` separated by `,` into a list of integers
map ( int , example_string . split ( ',' ) )
637
Convert a string of numbers 'example_string' separated by comma into a list of numbers
[ int ( s ) for s in example_string . split ( ',' ) ]
638
Flatten list `x`
x = [ i [ 0 ] for i in x ]
639
convert list `x` into a flat list
y = map ( operator . itemgetter ( 0 ) , x )
640
get a list `y` of the first element of every tuple in list `x`
y = [ i [ 0 ] for i in x ]
641
extract all the values of a specific key named 'values' from a list of dictionaries
results = [ item [ 'value' ] for item in test_data ]
642
get current datetime in ISO format
datetime . datetime . now ( ) . isoformat ( )
643
get UTC datetime in ISO format
datetime . datetime . utcnow ( ) . isoformat ( )
644
Merge all columns in dataframe `df` into one column
df . apply ( ' ' . join , axis = 0 )
645
pandas subtract a row from dataframe `df2` from dataframe `df`
pd . DataFrame ( df . values - df2 . values , columns = df . columns )
646
read file 'myfile.txt' using universal newline mode 'U'
print ( open ( 'myfile.txt' , 'U' ) . read ( ) )
647
print line `line` from text file with 'utf-16-le' format
print ( line . decode ( 'utf-16-le' ) . split ( ) )
648
open a text file `data.txt` in io module with encoding `utf-16-le`
file = io . open ( 'data.txt' , 'r' , encoding = 'utf-16-le' )
649
Join data of dataframe `df1` with data in dataframe `df2` based on similar values of column 'user_id' in both dataframes
s1 = pd . merge ( df1 , df2 , how = 'inner' , on = [ 'user_id' ] )
650
check if string `foo` is UTF-8 encoded
foo . decode ( 'utf8' ) . encode ( 'utf8' )
651
get the dimensions of numpy array `a`
a . shape
652
get the dimensions of numpy array `a`
N . shape ( a )
653
get the dimensions of array `a`
N . shape ( a )
654
get the dimensions of numpy array `a`
a . shape
655
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 ]
656
convert string of bytes `y\xcc\xa6\xbb` into an int
struct . unpack ( '<L' , 'y\xcc\xa6\xbb' ) [ 0 ]
657
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 ] ]
658
create a list with permutations of string 'abcd'
list ( powerset ( 'abcd' ) )
659
Convert string to boolean from defined set of strings
s in [ 'true' , '1' , 't' , 'y' , 'yes' , 'yeah' , 'yup' , 'certainly' , 'uh-huh' ]
660
replace special characters in url 'http://spam.com/go/' using the '%xx' escape
urllib . parse . quote ( 'http://spam.com/go/' )
661
Save plot `plt` as svg file 'test.svg'
plt . savefig ( 'test.svg' )
662
count the number of elements in array `myArray`
len ( myArray )
663
insert directory './path/to/your/modules/' to current directory
sys . path . insert ( 0 , './path/to/your/modules/' )
664
How to plot with x-axis at the top of the figure?
ax . xaxis . set_ticks_position ( 'top' )
665
Insert records in bulk from "table1" of "master" DB to "table1" of sqlite3 `cursor` object
cursor . execute ( 'INSERT OR REPLACE INTO master.table1 SELECT * FROM table1' )
666
Match regex '[a-zA-Z][\\w-]*\\Z' on string 'A\n'
re . match ( '[a-zA-Z][\\w-]*\\Z' , 'A\n' )
667
match regex '[a-zA-Z][\\w-]*$' on string '!A_B'
re . match ( '[a-zA-Z][\\w-]*$' , '!A_B' )
668
Convert hex string "deadbeef" to integer
int ( 'deadbeef' , 16 )
669
Convert hex string "a" to integer
int ( 'a' , 16 )
670
Convert hex string "0xa" to integer
int ( '0xa' , 16 )
671
Convert hex string `s` to integer
int ( s , 16 )
672
Convert hex string `hexString` to int
int ( hexString , 16 )
673
print variable `value ` without spaces
print ( 'Value is "' + str ( value ) + '"' )
674
Print a string `value` with string formatting
print ( 'Value is "{}"' . format ( value ) )
675
Jinja join elements of array `tags` with space string ' '
{ { tags | join ( ' ' ) } }
676
get a list of locally installed Python modules
help ( 'modules' )
677
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 ) ) ]
678
Sort a string `s` in lexicographic order
sorted ( s , key = str . upper )
679
sort string `s` in lexicographic order
sorted ( sorted ( s ) , key = str . upper )
680
get a sorted list of the characters of string `s` in lexicographic order, with lowercase letters first
sorted ( s , key = str . lower )
681
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' )
682
Reverse key-value pairs in a dictionary `map`
dict ( ( v , k ) for k , v in map . items ( ) )
683
decode unicode string `s` into a readable unicode literal
s . decode ( 'unicode_escape' )
684
convert list of strings `str_list` into list of integers
[ int ( i ) for i in str_list ]
685
convert a list with string `['1', '2', '3']` into list with integers
map ( int , [ '1' , '2' , '3' ] )
686
convert list with str into list with int
list ( map ( int , [ '1' , '2' , '3' ] ) )
687
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/' ) )
688
find all anchors with a hyperlink that matches the pattern '^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'
soup . find_all ( 'a' , href = re . compile ( '^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))' ) )
689
execute a jar file 'Blender.jar' using subprocess
subprocess . call ( [ 'java' , '-jar' , 'Blender.jar' ] )
690
insert row into mysql database with column 'column1' set to the value `value`
cursor . execute ( 'INSERT INTO table (`column1`) VALUES (%s)' , ( value , ) )
691
remove a substring ".com" from the end of string `url`
if url . endswith ( '.com' ) : url = url [ : ( - 4 ) ]
692
remove a substring ".com" from the end of string `url`
url = re . sub ( '\\.com$' , '' , url )
693
remove a substring ".com" from the end of string `url`
print ( url . replace ( '.com' , '' ) )
694
remove a substring `suffix` from the end of string `text`
if ( not text . endswith ( suffix ) ) : return text return text [ : ( len ( text ) - len ( suffix ) ) ]
695
print each first value from a list of tuples `mytuple` with string formatting
print ( ', ,' . join ( [ str ( i [ 0 ] ) for i in mytuple ] ) )
696
clamping floating number `my_value` to be between `min_value` and `max_value`
max ( min ( my_value , max_value ) , min_value )
697
split a unicode string `text` into a list of words and punctuation characters with a regex
re . findall ( '\\w+|[^\\w\\s]' , text , re . UNICODE )
698
execute raw sql queue '<sql here>' in database `db` in sqlalchemy-flask app
result = db . engine . execute ( '<sql here>' )
699
quit program
sys . exit ( 0 )