pandas模組篇(之二)
阿新 • • 發佈:2020-09-03
今日內容概要
- 布林選擇器
- 索引
- 資料對齊
- 資料操作(增出改查)
- 算術方法
- DataFrame(Excel表格資料)
布林選擇器
import numpy as np import pandas as pd res = pd.Series([True,False,False,True,False]) price = pd.Series([321321,123,324,5654,645]) # 掌握 price[res] 0 321321 3 5654 dtype: int64 # 瞭解 price|res 0 True 1 True 2 True 3 True 4 True dtype: bool price&res 0 True 1 False 2 False 3 False 4 False dtype: bool # 需要掌握 (price > 100) & (price < 700) 0 False 1 True 2 True 3 False 4 True dtype: bool price[(price > 100) & (price < 700)] 1 123 2 324 4 645 dtype: int64
索引及標籤
res1 = pd.Series({'a':111,'b':222,'c':333,'d':444,'e':555}) res1 a 111 b 222 c 333 d 444 e 555 dtype: int64 # 索引取值 res1[0] 111 # 標籤取值 res1['a'] 111 # 獲取所有的標籤 res1.index Index(['a', 'b', 'c', 'd', 'e'], dtype='object') # 給標籤加列名稱 res1.index.name = 'STA' res1 STA a 111 b 222 c 333 d 444 e 555 dtype: int64 # data_range時間間隔 res2 = pd.date_range('2020-01-01','2020-12-01',freq='M') # frep後面按照指定的時間間隔(年'Y',月'M',日'D') res2 DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30', '2020-05-31', '2020-06-30', '2020-07-31', '2020-08-31', '2020-09-30', '2020-10-31', '2020-11-30'], dtype='datetime64[ns]', freq='M') # 還可以將日期作為Series的標籤 res3 = pd.Series([111,222,333,444,555],index=res3) res3 2020-01-31 111 2020-02-29 222 2020-03-31 333 2020-04-30 444 2020-05-31 555 Freq: M, dtype: int64 res3.index.name = '日期' 日期 2020-01-31 111 2020-02-29 222 2020-03-31 333 2020-04-30 444 2020-05-31 555 Freq: M, dtype: int64
整數索引
1 整數索引 x1 = pd.Series(np.arange(11)) x1 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 dtype: int32 x2 = x1[4:] x2 4 4 5 5 6 6 7 7 8 8 9 9 10 10 dtype: int32 ################################################################################################## # 索引取值 # x1[1] # 報錯 '''針對取值操作,以後需要用特定方法來約束''' # iloc按照索引的方式取值 # loc按照標籤的方式取值 # x1.iloc[1] # 1 x1.loc[3] # 3 '''非常重要,一定要記憶''' ###################################################################################################
資料對齊
a1 = pd.Series([12,23,34,45],index=['c','a','d','b'])
a2 = pd.Series([11,20,10,30],index=['d','c','a','b'])
a1 + a2
執行結果:
a 33
b 75
c 32
d 45
dtype: int64
# 可以通過這種索引對齊直接將兩個Series物件進行運算
a3 = pd.Series([11,20,10,14],index=['d','c','a','e'])
a1 + a3
執行結果:
a 33.0
b NaN
c 32.0
d 45.0
e NaN
dtype: float64
# a1和a3的索引不一致,所以最終的執行會發現e索引對應的值無法運算,就返回了NAN,一個缺失值
'''
疑問:為什麼運算完之後資料型別會由原來的int64變成float64?
因為NaN其實是float型別
type(np.nan)
結果是:float
'''
資料操作
'''增刪改查'''
a3= pd.Series([11,20,10,14],index=['d','c','a','e'])
a3
d 11
c 20
a 10
e 14
dtype: int64
# 查
a3.loc['a']
10
# 改
a3.iloc[2]= 100
a3
d 11
c 20
a 100
e 14
dtype: int64
# 增
# 方式1:append不修改原資料
a3.append(pd.Series([66],index=['e']))
d 11
c 20
a 100
e 14
e 66
dtype: int64
#方式2:set_value直接修改原資料
a3.set_value('f',999) # 會有一個提示 如果不想有這個提示需要配置
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: FutureWarning: set_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead
d 11
c 20
a 100
e 14
f 999
dtype: int64
a3
d 11
c 20
a 100
e 14
f 999
dtype: int64
# 刪: del關鍵字作用的也是原資料
del a3['f']
a3
d 11
c 20
a 100
e 14
dtype: int64
靈活的算術方法
"""
針對加減乘除等數學運算
可以直接使用符號
也可以使用提供的方法名(可以有額外的功能)
add
sub
div
mul
"""
b1 = pd.Series([12,23,34], index=['c','a','b'])
b3 = pd.Series([11,20,10,14], index=['d','c','a','b'])
b1
c 12
a 23
b 34
dtype: int64
b3
d 11
c 20
a 10
b 14
dtype: int64
tes = b1 + b3
tes
a 33.0
b 48.0
c 32.0
d NaN
dtype: float64
tes1 = b1*b3
tes1
a 230.0
b 476.0
c 240.0
d NaN
dtype: float64
b1.add(b3,fill_value=666)
b1
c 12
a 23
b 34
dtype: int64
b3
d 11
c 20
a 10
b 14
dtype: int64
fill_value
b1.add(b3,fill_value=0) # 在執行之前找出呼叫該方法的Series當中的缺失值補全後再運算
a 33.0
b 48.0
c 32.0
d 11.0
dtype: float64
b1.mul(b3,fill_value=1)
a 230.0
b 476.0
c 240.0
d 11.0
dtype: float64
DataFrame
表格型資料結構,相當於一個二維陣列,含有一組有序的列也可以看作是由Series組成
基本使用
# 建立Dataframe有很多中方式,但是一般情況下我們都不需要自己建立DataFrame而是將excel檔案直接引導成DataFrame
# 方式1 傳字典字典的鍵會變成表格的列名稱 行名稱預設是索引
import numpy as np
import pandas as pd
res = pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
res
one two
0 1 4
1 2 3
2 3 2
3 4 1
# 取值
res['one'] # 預設是Series的展示形式
0 1
1 2
2 3
3 4
Name: one, dtype: int64
res[['two']] # 再加[]就會變成表格的形式
two
0 4
1 3
2 2
3 1
res['two'][1] # 第一個中括號裡面是列 第二個中括號裡面是行
3
# 方式2: 直接傳Series 如果Series有自定義的標籤 那麼生成的DataFrame列名稱採用的就是標籤名
res1 = pd.DataFrame({'one':pd.Series([1,2,3],index=['c','b','a']),'two':pd.Series([1,2,3],index=['b','a','c'])})
res1
one two
a 3 2
b 2 1
c 1 3
# 方式3:自定義行列 index行 columns列
pd.DataFrame(np.array([[10,20,30],[40,50,60]]),index=['a','b'],columns=['c1','c2','c3'])
c1 c2 c3
a 10 20 30
b 40 50 60
arange
# 方式4:列表中有幾個元素就會生成幾行資料 不指定行列預設都是用索引表示
pd.DataFrame([np.arange(1,8),np.arange(11,18),np.arange(21,28)])
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
1 11 12 13 14 15 16 17
2 21 22 23 24 25 26 27
# 方式5:會自動找行列的對應位置 沒有的用NaN表示缺失值
s1 = pd.Series(np.arange(1,9,2))
s2 = pd.Series(np.arange(2,10,2))
s3 = pd.Series(np.arange(5,7),index=[1,2])
s1
0 1
1 3
2 5
3 7
dtype: int32
s2
0 2
1 4
2 6
3 8
dtype: int32
s3
1 5
2 6
dtype: int32
df5 = pd.DataFrame({'c1':s1,'c2':s2,'c3':s3})
df5
c1 c2 c3
0 1 2 NaN
1 3 4 5.0
2 5 6 6.0
3 7 8 NaN
'''以上建立房事後都僅僅做一個瞭解即可,因為工作在中dataframe的資料一般都是來自於讀取外部檔案資料'''
常見屬性及方法
1.index 行索引
2.columns 列索引
3.T 轉置
4. values 值索引
5.describe 快速統計
# index獲取行索引
df5.index
Int64Index([0,1,2,3],dtype='int64')
# columns獲取列索引
df5.columns
Index(['c1', 'c2', 'c3'], dtype='object')
# T轉置 行列互換
df5.T
0 1 2 3
c1 1.0 3.0 5.0 7.0
c2 2.0 4.0 6.0 8.0
c3 NaN 5.0 6.0 NaN
df5
c1 c2 c3
0 1 2 NaN
1 3 4 5.0
2 5 6 6.0
3 7 8 NaN
values
# values獲取表格資料 組織成二維陣列的形式
df5.values
array([[ 1., 2., nan],
[ 3., 4., 5.],
[ 5., 6., 6.],
[ 7., 8., nan]])
# describe常見的數學統計
df5.describe()
c1 c2 c3
count 4.000000 4.000000 2.000000
mean 4.000000 5.000000 5.500000
std 2.581989 2.581989 0.707107
min 1.000000 2.000000 5.000000
25% 2.500000 3.500000 5.250000
50% 4.000000 5.000000 5.500000
75% 5.500000 6.500000 5.750000
max 7.000000 8.000000 6.000000