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
轉載于:https://www.cnblogs.com/-wenli/p/10271475.html