處理丟失數(shù)據(jù)
由np.nan 填充丟失的數(shù)據(jù)
df.dropna(axis=0, how='any')
- axis 根據(jù)行或者列丟棄摆寄,0 是行,1是列
- how坯门,指定丟棄行為
- any微饥,只要有一個(gè)nan就丟棄,古戴,默認(rèn)
- all欠橘,所有的都為nan才丟棄
df.fillna(value=0), 為nan填上數(shù)據(jù)
- value, 指定需要填入的數(shù)據(jù)
其他相關(guān)方法
- df.isnull() 檢查dataFrame中是否有缺失數(shù)據(jù)
- np.any(df.isnull() = True) 針對(duì)超大表格,找到是否有nan
Panda導(dǎo)入導(dǎo)出
可以讀取的格式
- read_csv 這個(gè)常用
- read_excel
- read_hdf
- read_pickle python自帶壓縮格式
- read_json
可以導(dǎo)出的格式
- to_csv
- to_json
data = pd.read_csv("\*.csv")
read 進(jìn)來以后會(huì)自動(dòng)加上索引
data.to_csv("***.csv") 直接使用dataframe調(diào)用to_*** 來輸出
合并多個(gè)DataFrame
df10 = pd.DataFrame(np.ones((3,4))*0, columns=['a', 'b', 'c', 'd'] )
df11 = pd.DataFrame(np.ones((3,4))*1, columns=['a', 'b', 'c', 'd'] )
df12 = pd.DataFrame(np.ones((3,4))*1, columns=['b', 'c', 'd', 'e'] )
res = pd.concat([df10 , df11], axis=0, ignore_index=Ture)
- asix 為0是為上下合并(有相同的列)现恼,為1時(shí)為橫向的合并(有相同的行)
- ignore_index=True 對(duì)index重新安排, 為False的時(shí)候會(huì)保留之前的index
- join, ['inner', 'outer'] 在contact的時(shí)候處理不一樣的行或列數(shù)據(jù)
** res = pd.concat([df1, df2]), 默認(rèn)會(huì)有廣播機(jī)制并使用nan填充 相當(dāng)于['outer'], res = pd.concat([df1, df2], join='outer')
** 'inner', concat 之后就只包含相同的部分 - join_axes, res = pd.concat([df10, df11, df12], axis=1, join_axes=[df10.index])
** 使用join_axes 指定的index進(jìn)行合并肃续,對(duì)于df11沒有的index使用nan進(jìn)行填充 ,對(duì)于df10中不存在的忽略掉
** 對(duì)于列的話需要使用 df10.columns
** 注意這里和join的區(qū)別 - append叉袍,豎向或者橫向的添加數(shù)據(jù)
res = df1.append(df2, ignore_index=True)
res = df1.appends(s1, ignore_index=True), 一行一行的添加
Merge多個(gè)DataFrame
res= pd.merge(df1, df2, on='key')
pd.merge(df1, df2, on=['key1', 'key2'])
- 可以指定合并的方法始锚,
** inner,key的值必須一樣的才和并
** outer, 不管值是不是一樣都會(huì)合并喳逛, 對(duì)于不一樣的值填充NAN
** left疼蛾, 只靠一邊的數(shù)據(jù),另一邊不一樣的填充NAN
** right - indicator, 顯示是如何merge的
- index, 通過對(duì)比index來進(jìn)行merge
res = pd.merge(df21, df22, left_index=True, right_index=True, how='outer')
- left_index 考慮df21中的index
- right_index 考慮df22中的index
合并過程中如何處理重復(fù)數(shù)據(jù)(index名稱相同艺配,但是內(nèi)涵不同的數(shù)據(jù))
使用參數(shù)suffixes察郁, 對(duì)于那些列名相同,但是又不在merge范圍內(nèi)的數(shù)據(jù)
res = pd.merge(df20, df21, on='d', suffixes=['_df20', '_df21'], how='inner')
Pandas Plot
其實(shí)還是使用matplotlib來畫圖的转唉,但是可以集成到pandas的使用中去
data = pd.Series(np.random.randn(1000), index=np.arange(1000))
data.plot()
plt.show()
首先是data.plot()皮钠,然后在調(diào)用plt.show() 將圖片顯示出來,這種方法對(duì)于Series和DataFrame都適用
畫其他類型的圖:
plot method:“bar”, “hist”赠法, “box”麦轰, “area”
data.plot.scatter(x='a', y='b')
將兩組數(shù)據(jù)畫在同一張圖上:重點(diǎn)在于指定ax
ax = data.plot.scatter(x='a', y='b',color='blue', label='Class 1')
data.plot.scatter(x='c', y='d',color='red', label='Class 2', ax=ax)