import pandas as pd
基本创建
s = pd. Series( [ 1 , 2 , 3 , 4 , 5 , 6 ] )
print ( s)
s = pd. Series( [ 'a' , 'b' , 'c' , 'd' , 'e' ] , index= [ 100 , 200 , 100 , 400 , 500 ] )
print ( s)
d = { 'b' : 1 , 'a' : 0 , 'c' : 2 }
s = pd. Series( d)
print ( s)
s = pd. Series( np. array( [ 1 , 2 , 3 , 4 , 5 ] ) , index= [ 'a' , 'b' , 'c' , 'd' , 'e' ] )
print ( s[ 1 : ] )
print ( s[ : - 1 ] )
print ( s[ 1 : ] + s[ : - 1 ] )
df = pd. DataFrame( np. arange( 12 ) . rshape( ( 3 , 4 ) ) )
print ( df)
print ( df. index)
print ( df. columns)
print ( df. dtypes)
print ( df. sample( 10 ) )
data =
{ 'state' : [ 'Ohio' , 'Ohio' , 'Ohio' , 'Nevada' , 'Nevada' ] ,
'year' : [ 2000 , 2001 , 2002 , 2001 , 2002 ] ,
'pop' : [ 1.5 , 1.7 , 3.6 , 2.4 , 2.9 ] }
frame = pd. DataFrame( data)
print ( frame)
frame1 = pd. DataFrame( data, columns= [ 'year' , 'state' , 'pop' ] )
print ( frame1)
frame2 = pd. DataFrame( data, columns= [ 'year' , 'state' , 'pop' , 'debt' ] , index= [ 'one' , 'two' , 'three' , 'four' , 'five' ] )
print ( frame2)
print ( frame2[ 'state' ] )
frame2[ 'debt' ] = 16.5
print ( frame2)
frame2[ 'new' ] = frame2[ 'debt' ] * frame2[ 'pop' ]
print ( frame2)
处理数据
df = pd. DataFrame( np. arange( 12 ) . reshape( ( 3 , 4 ) ) , columns= [ 'A' , 'B' , 'C' , 'D' ] )
print ( df. T)
df1 = df. sort_index( axis= 1 , ascending= False )
print ( df1)
df2 = df. sort_index( axis= 0 , ascending= False )
print ( df2)
df3 = df. sort_values( by= 'A' , ascending= False )
print ( df3)
print ( df[ 'A' ] )
print ( df. B)
print ( df[ 1 : 3 ] )
print ( df. loc[ 0 : 1 , [ 'A' , 'C' ] ] )
print ( df. iloc[ 1 : 3 , 1 : 3 ] )
df. iloc[ 1 , 1 ] = 999
df[ df. A> 4 ] = 0
df = pd. DataFrame( np. arange( 24 ) . reshape( ( 6 , 4 ) ) , columns= [ 'A' , 'B' , 'C' , 'D' ] )
df. iloc[ 0 , 1 ] = np. nan
df. iloc[ 1 , 2 ] = np. nan
print ( df. dropna( axis= 0 , how= 'any' ) )
print ( df. dropna( axis= 1 , how= 'all' ) )
print ( df. fillna( value= 0 ) )
print ( np. any ( df. isnull( ) ) == True )
print ( df. any ( ) )
print ( df. all ( ) )
表格合并
df1 = pd. DataFrame( np. ones( ( 3 , 4 ) ) * 0 , columns= [ 'a' , 'b' , 'c' , 'd' ] )
df2 = pd. DataFrame( np. ones( ( 3 , 4 ) ) * 1 , columns= [ 'a' , 'b' , 'c' , 'd' ] )
df3 = pd. DataFrame( np. ones( ( 3 , 4 ) ) * 2 , columns= [ 'a' , 'b' , 'c' , 'd' ] )
df = pd. concat( [ df1, df2, df3] , axis= 0 , ignore_index= True )
print ( df)
df = pd. concat( [ df1, df2] , join= 'outer' )
print ( df)
df = pd. concat( [ df1, df2] , join= 'inner' )
print ( df)
画图
s = pd. Series( np. random. randn( 1000 ) , index= np. arange( 1 , 1001 ) )
s = s. cumsum( )
s. plot( )
plt. show( )
df = pd. DataFrame( np. random. randn( 1000 , 5 ) , index= np. arange( 1 , 1001 ) , columns= list ( 'ABCDE' ) )
df = df. cumsum( )
df. plot( )
plt. show( )