Pandas 學習筆記(一)
阿新 • • 發佈:2021-01-24
Pandas 學習筆記(一)
文章目錄
生成物件
-
s = pd.Series([1,2,np.nan,5,6])
用值列表生成Series時,Pandas預設自動生成整數索引
-
df = pf.DataFrame(np.random.randn(6,4),index=dates,columns=list(‘ABCD’))
也可以用Series生成DataFrame
df2=({
‘A’ :1,
‘B’ : pd.Timestamp(“20210123”) ,
‘C’ : pd.Series(1,index = list(range(4)))
})
DataFrame 的列可以具有不同的屬性
檢視資料
-
df.head()
df.head()展示資料的頭部
-
df.tail()
df.tail()展示尾部資料
-
df.index
顯示索引
-
df.columns
顯示列名
-
df.describe()
快速檢視資料的統計摘要
-
df.T
轉置資料
-
df.sort_index(axis = 1,ascending = False)
按軸排序
-
df.sort_values(by = ‘B’)
按值排序
選擇
-
df[‘A’]
選擇A列,生成Series
-
df[0:3]
使用[]切片行
-
df.loc[dates[0]]
按照標籤提取一行資料
-
df.loc[:,[‘A’,'B]]
用標籤選擇多列資料
-
df.at[dates[0],‘A’]
快速訪問標量
缺失值
Pandas 用 np.nan 表示缺失資料。 計算時,預設不包含空值
刪除含有缺失值的行
df.dropna(how = 'any')
填充缺失值
df.fillna(value = 5)
提取 nan 值的布林掩碼
pd.isna(df)
合併
- conact()
- join()
- append()
分組
group by 一般指以下的處理過程
- 分割 :將資料分割成多組
- 應用 :為每組單獨應用函式
- 組合 :將處理結果組合成一個數據結構
視覺化
-
ts = ts.cumsum() ts.plot() #DataFrame 的 plot() 方法會快速繪製帶標籤的列
輸入輸出
-
df.to_csv('xxx.csv')
-
df.to_hdf('foo.h5','df')
-
df.to_excel('xxx.xlsx',sheet_name = 'Sheet1') pd.read_excel('xxx.xlsx','Sheet1',index_col = None ,na_valeus = ['NA'])