pandas學習(一)
Pandas基本數據結構
Series類型數據
Dataframe類型
基本操作
Pandas基本數據結構
兩種常用數據結構: Series 一維數組,與Numpy中的一維array類似,二者與Python基本數據結構List很相似,Series能保存不同數據類型,字符串,boolbean值、數字等都能保存在Series中 DataFrame 二維的表格型數據結構。很多功能與R中的data frame類似。可以將DataFrame理解為Series的容器。
Series類型數據
默認情況下下標是數字(可以使用額外參數指定),類型是統一的 第一個參數就是一維的數組,你可以通過傳入列表,也可以使用numpy生成
初始化series
第一種方法通過numpy生成。
import pandas as pd s=pd.Series(np.arange(0,6)) print(s)
0 0 1 1 2 2 3 3 4 4 5 5
注意:默認沒有指定下標,所以從零開始。
第二種方法,通過傳入列表。
import pandas as pd s=pd.Series([1,3,6,np.nan,44,1])#np.nan是空值 print(s)
0 1.0 1 3.0 2 6.0 3 NaN 4 44.0 5 1.0
增加行標簽
import pandas as pd s=pd.Series([1,3,6,np.nan,44,1],index='a','b','c','d','e','f') print(s) print(s.index)#行標簽名 print(s.values)#所有值 print(s[0])#通過下標訪問 print(s[1:4])#通過切片訪問
b 1.0 f 3.0 e 6.0 d NaN a 44.0 c 1.0 dtype: float64 Index(['b', 'f', 'e', 'd', 'a', 'c'], dtype='object') [ 1. 3. 6. nan 44. 1.] 1.0 f 3.0 e 6.0 d NaN
Dataframe類型
第一種創建方式
DataFrame則是個二維結構,這里首先構造一組時間序列,作為我們第一組的下標
import pandas as pd date1= pd.date_range('20190114',periods=6) print(date1)
DatetimeIndex(['2019-01-14', '2019-01-15', '2019-01-16', '2019-01-17', '2019-01-18', '2019-01-19'], dtype='datetime64[ns]', freq='D')
然后創建一個Dataframe結構,默認沒有指定下標
不指定index和clumns時,默認從零開始
第一個參數其實就是一個二維數組,使用numpy可以生成
import pandas as pd date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.random.randn(6,4))#生成6行4列 print(df)
0 1 2 3 0 0.019099 0.685904 -1.748481 0.944940 1 -1.754479 -0.229799 -0.581667 0.594955 2 0.302477 0.017760 0.747850 -0.516475 3 0.980783 0.215233 0.905535 -0.844875 4 -1.004730 -0.745205 0.409685 0.044063 5 1.302190 -0.355871 -0.009040 0.575193
指定下標,當然這里也可以用別的一維列表來指定行下標,不一定要使用時間序列。
import pandas as pd date1= pd.date_range('20190114',periods=6 df=pd.DataFrame(np.random.randn(6,4),index=date1,columns=['a','b','c','d']) #index為行下標,columns為列下標 print(df)
a b c d 2019-01-14 -0.936922 0.727929 -0.021961 -1.042981 2019-01-15 -0.428813 0.304645 0.397171 1.601983 2019-01-16 1.529067 -0.745912 -0.028289 -1.497475 2019-01-17 -1.756153 -0.870725 -0.161252 -1.607953 2019-01-18 -1.474564 0.364908 1.038624 0.247872 2019-01-19 -0.071704 1.684375 -0.745785 0.301716
第二種創建方式
除了向Dataframe中傳入二維數組,我們也可以使用字典傳入數據
字典的每一個key代表一列,其value可以使各種能夠轉化為Series的對象
與Series要求所有的類型都一致不同,DataFrame只要求每一列數據的格式相同
import pandas as pd df1 = pd.DataFrame({'A':1., 'B':pd.Timestamp('20190114'), 'C':np.array([3]*4,dtype='int32'), 'E':pd.Categorical(["test","train","test","train"]), 'F':'foo', 'G':pd.Series([1,2,3,4]) } ) print(df1)
A B C E F G 0 1.0 2019-01-14 3 test foo 1 1 1.0 2019-01-14 3 train foo 2 2 1.0 2019-01-14 3 test foo 3 3 1.0 2019-01-14 3 train foo 4
簡單操作
import pandas as pd df1 = pd.DataFrame({'A':1., 'B':pd.Timestamp('20190114'), 'C':np.array([3]*4,dtype='int32'), 'E':pd.Categorical(["test","train","test","train"]), 'F':'foo', 'G':pd.Series([1,2,3,4]) } )
print(df1.dtypes)#查看類型,查看每列的類型 print(df1.index)#查看行下標 print(df1.columns)#查看列下標 print(df1.values)#查看所有值 print(df1.describe())#查看平均數,方差等計算值
A float64 B datetime64[ns] C int32 E category F object G int64 dtype: object RangeIndex(start=0, stop=4, step=1) Index(['A', 'B', 'C', 'E', 'F', 'G'], dtype='object') [[1.0 Timestamp('2019-01-14 00:00:00') 3 'test' 'foo' 1] [1.0 Timestamp('2019-01-14 00:00:00') 3 'train' 'foo' 2] [1.0 Timestamp('2019-01-14 00:00:00') 3 'test' 'foo' 3] [1.0 Timestamp('2019-01-14 00:00:00') 3 'train' 'foo' 4]] A C G count 4.0 4.0 4.000000 mean 1.0 3.0 2.500000 std 0.0 0.0 1.290994 min 1.0 3.0 1.000000 25% 1.0 3.0 1.750000 50% 1.0 3.0 2.500000 75% 1.0 3.0 3.250000 max 1.0 3.0 4.000000
基本操作
訪問數據
通過標簽選擇數據
df.loc[index,columns],通過行和列的標簽來選擇數據
使用loc,select by label
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) print(df.loc['2019-01-15','b'])#通過行下標和列下標確定一個值
print(df.loc[:,'b'])#選擇所有行,列為'b'
print(df.loc['2019-01-18',:])#選擇所有列,行為'2019-01-18'
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
7
2019-01-14 3 2019-01-15 7 2019-01-16 11 2019-01-17 15 2019-01-18 19 2019-01-19 23 Freq: D, Name: b, dtype: int32
a 18 b 19 c 20 d 21
Name: 2019-01-18 00:00:00, dtype: int32
通過位置
使用iloc,select by position
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) print(df.iloc[0])#第一行 print(df.iloc[1])#第二行 print(df.iloc[0:4])#第一行到第四行
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a 2 b 3 c 4 d 5 Name: 2019-01-14 00:00:00, dtype: int32
a 6 b 7 c 8 d 9 Name: 2019-01-15 00:00:00, dtype: int32
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17
結合前面兩種方法:通過標簽和下標來選擇
mixed selection:ix
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) print(df.ix[0:3,['a','b']])
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a b 2019-01-14 2 3 2019-01-15 6 7 2019-01-16 10 11
條件選擇
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) print(df[df.a>8])#前面的df為范圍,后面的df.a選擇‘a’列 print(df[df['b']==11]) print(df[(df.a==10)&(df.c==12)]) print(df.a[df.b>8])
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a b c d 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a b c d 2019-01-16 10 11 12 13 a b c d
2019-01-16 10 11 12 13
2019-01-16 10 2019-01-17 14 2019-01-18 18 2019-01-19 22 Freq: D, Name: a, dtype: int32
行操作
基本操作
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) # 查看前幾行或者后幾行,如果不指定參數,默認五行 print(df.head(3)) print(df.tail(2))
#print(df.loc['a']) #查看指定行,可以通過下標和標簽兩種形式指定 print(df[0:1]) print(df['2019-01-14':'2019-01-17']) # 也可以使用使用iloc # print(df.iloc[0]) # print(df.iloc[1]) # print(df.iloc[0:4])
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13
a b c d 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25
a b c d 2019-01-14 2 3 4 5
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17
添加一行
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) date={'a':49,'b':34,'c':12,'d':98}#添加的一行數據 s=pd.Series(date)#生成一維的pd數據 ##一定要給行命名,才能添加成功 s.name='2019-01-20 00:00:00' df=df.append(s)#添加 print(df)
a b c d 2019-01-14 2 3 4 5 2019-01-15 6 7 8 9 2019-01-16 10 11 12 13 2019-01-17 14 15 16 17 2019-01-18 18 19 20 21 2019-01-19 22 23 24 25 a b c d 2019-01-14 00:00:00 2 3 4 5 2019-01-15 00:00:00 6 7 8 9 2019-01-16 00:00:00 10 11 12 13 2019-01-17 00:00:00 14 15 16 17 2019-01-18 00:00:00 18 19 20 21 2019-01-19 00:00:00 22 23 24 25 2019-01-20 00:00:00 49 34 12 98
刪除一行
沒有標簽的情況,使用下標刪除
df = pd.DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D']) print(df) #Drop rows by index # df=df.drop([0]) #刪除第一行 # df=df.drop([1,2]) #刪除2、3行 # print(df)
有標簽的情況,使用標簽刪除
df = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['A', 'B', 'C', 'D']) print(df) #Drop rows by index # df=df.drop(['a'])#刪除第一行 # df=df.drop(['b','c'])#刪除2和3行 print(df)
在有時間序列的下標情況下,使用下標和標簽的方法 ,都會出錯,暫時不知道什么問題
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d'])
df=df.drop([1])
print(df)
df=df.drop(['2019-01-15'])
print(df)
列操作
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) # print(df.columns) #輸出所有列標簽 # print(df['a']) #輸出'a'這一列 # print(df['a'][1])#'a'列的第二行 # print(df['a'][:3]) #'a'列的第一行到第三行 # print(df[['a','b']])#'a'列與'b'列
增加一列
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) print(df.columns) df['序列']=range(1,len(df)+1)#添加新的列,首先要知道一列需要多少個元素,再按要求生成 print(df)
刪除某一列
date1= pd.date_range('20190114',periods=6) df=pd.DataFrame(np.arange(2,26).reshape(6,4),index=date1,columns=['a','b','c','d']) print(df) df=df.drop('序列',axis=1)
.drop()方法
需要注意的地方
drop方法既可以保留原數據塊中的所選列,也可以刪除,這取決於參數inplace
df = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['A', 'B', 'C', 'D']) print(df) # Drop rows by index date3=df.drop(['a'])#刪除第一行 print(date3) print(df)
默認情況下,使用drop方法刪除后,會返回被刪除的一行,原數據也被刪除
A B C D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 A B C D b 4 5 6 7 c 8 9 10 11 A B C D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11
當inplace=True時.drop()執行內部刪除,不返回任何值,原數據發生改變
df = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['A', 'B', 'C', 'D']) print(df) # Drop rows by index date3=df.drop(['a'],inplace=True)#刪除第一行 print(date3) print(df)
運行結果顯示沒有輸出被刪除的一行,為none,原數據被刪除
A B C D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 None A B C D b 4 5 6 7 c 8 9 10 11
.pop()方法
.pop方法可以將所選列從原數據塊中彈出,原數據塊不再保留該列
df = pd.DataFrame(np.arange(12).reshape(3,4),index=['a','b','c'],columns=['A', 'B', 'C', 'D']) print(df) date=df.pop('A') print(date) print(df)
結果顯示彈出'A'列,並刪除
A B C D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11
a 0 b 4 c 8 Name: A, dtype: int32
B C D a 1 2 3 b 5 6 7 c 9 10 11