數(shù)據(jù)分析工具Pandas

Pandas簡介

什么是Pandas

Pandas的名稱來自于面板數(shù)據(jù)(panel data)和Python數(shù)據(jù)分析(data analysis)。
Pandas是一個強大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,基于NumPy構(gòu)建,提供了高級數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)操作工具,它是使Python成為強大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一。

一個強大的分析和操作大型結(jié)構(gòu)化數(shù)據(jù)集所需的工具集
基礎(chǔ)是NumPy,提供了高性能矩陣的運算
提供了大量能夠快速便捷地處理數(shù)據(jù)的函數(shù)和方法
應(yīng)用于數(shù)據(jù)挖掘,數(shù)據(jù)分析
提供數(shù)據(jù)清洗功能
官網(wǎng):http://pandas.pydata.org

導(dǎo)入pandas
import pandas as pd
pd別名業(yè)界約定


Pandas的數(shù)據(jù)結(jié)構(gòu)

Series

Series是一種類似于一維數(shù)組的對象,組成:
一組數(shù)據(jù)(各種NumPy數(shù)據(jù)類型)
一組與之對應(yīng)的索引(數(shù)據(jù)標(biāo)簽)
索引(index)在左,數(shù)據(jù)(values)在右
索引是自動創(chuàng)建的

1.通過list構(gòu)建series

ser_obj = pd.series(range(10,30))#不指定索引的話,默認從0開始
print(ser_obj)
print(ser_obj.head(3))
print(type(ser_obj))

image.png

2.通過dict構(gòu)建series

dict = {"Java":80,"php":85,"python":90}
ser_obj = pd.Series(dict)
print(ser_obj)

image.png

3.獲取數(shù)據(jù)和索引
ser_obj.inde 和 ser_obj.values

#獲取數(shù)據(jù)
print(ser_obj.values)
#獲取索引
print(ser_obj.index)

image.png

4.通過索引獲取數(shù)據(jù)
ser_obj[idx]

#通過索引獲取數(shù)據(jù)
print(ser_obj1[0])
print(ser_obj1[3])

image.png

5.設(shè)置名稱
對象名:ser_obj.name 給整個表起名字
對象索引名:ser_obj.index.name給某一列

ser_obj1.name = 'score'
ser_obj1.index.name = 'subject'
image.png

DataFrame

一個表格型的數(shù)據(jù)結(jié)構(gòu),它含有一組有序的列,每列可以是不同類型的值。DataFrame既有行索引也有列索引,數(shù)據(jù)是以二維結(jié)構(gòu)存放的。
類似多維數(shù)組/表格數(shù)據(jù) (如,excel, R中的data.frame)
每列數(shù)據(jù)可以是不同的類型
索引包括列索引和行索引

1.通過ndarray構(gòu)建DataFrame

arr_obj = np.random.rand(3,4)
df_obj = pd.DataFrame(arr_obj)
print(df_obj)
print(df_obj.head(2)) #看前兩行
image.png

2.通過dict構(gòu)建DataFrame

dict2 = { "A":1,
         "B":pd.Timestamp("20180124"),
         "C":pd.Series(range(10,14),dtype="float64"),
         "D":['Java','Python','C++',"php"],
         "E":np.array([3]*4)    
}
df_obj2 = pd.DataFrame(dict2)
print(df_obj2)

image.png

3.通過索引獲取列數(shù)據(jù)

print(df_obj2['D'])
print(type(df_obj2['D']))
print(type(df_obj2['C']))
print(type(df_obj2['A']))
print(df_obj2.A)

image.png

4.增加列數(shù)據(jù)

df_obj2['F'] = {"金水區(qū)":80,"二七區(qū)":75,"中原區(qū)":72,"高新區(qū)":88}
print(df_obj2)

image.png

列數(shù)據(jù)增加

df_obj2["H"] = df_obj["C"]+10

image.png

5.刪除列

del(df_obj2['E'])
print(df_obj2)
image.png

Pandas的索引操作

索引對象Index

Series和Frame中的索引都是Index對象
索引對象不可變,保證了數(shù)據(jù)的安全
1.index指定行索引名
不指定索引的話,默認從0開始

ser_obj3 = pd.Series([1,2,3,6,7,8],index=['a','b','c','d','e','f'])
print(ser_obj3)

image.png

2.行索引

print(ser_obj3['c'])
print(ser_obj3[3])

image.png

3.切片索引
注意,按索引名切片操作時,是包含終止索引的。

print(ser_obj3['b':'e'])
print(ser_obj3[1:4])

image.png

4.不連續(xù)索引

print(ser_obj3[['b','e','f']])
image.png

5.布爾索引

bool_arr = ser_obj3 > 3
print(bool_arr)
image.png

DataFrame索引

1.columns指定列索引名

df_obj5 = pd.DataFrame(np.random.randn(5,4),index = ['A','B','C','D','E'],columns=['a','b','c','d']) 
print(df_obj5)

image.png

2.列索引

print(df_obj5['b'])
image.png
print(df_obj5['b']['D'])
image.png

3.不連續(xù)索引

print(df_obj5[['a','c']])
image.png

高級索引:標(biāo)簽、位置和混合

1.loc標(biāo)簽索引
loc是基于標(biāo)簽名的索引,也就是我們自定義的索引名

print(df_obj5['b'])
print(df_obj5[['b','d']])  # 不連續(xù)
print(df_obj5.loc['A':'D','b':'d']) # 切片
image.png
print(ser_obj3['a'])
print(ser_obj3.loc['a'])
print(ser_obj3.loc[['a','b']])  # 不連續(xù)
print(ser_obj3.loc['b':'d'])  # 切片

image.png
print(df_obj5['a']['A'])
print(df_obj5[df_obj5['a']!=df_obj5['a'][2]])

image.png

2.iloc位置索引
作用與loc一樣,不過是給予索引編號來索引

print(ser_obj3.iloc[1:3])
image.png
print(df_obj5.iloc[0:2,1:4])

image.png

3.ix標(biāo)簽與位置混合索引
ix是以上二者的綜合,既可以使用索引編號,又可以使用自定義索引,要視情況不同來使用
如果索引既有數(shù)字又有英文,容易導(dǎo)致定位的混亂,那么這種方式不建議使用的

# Series 對象
print(ser_obj3.ix[0:3])
print(ser_obj3.ix['b':'e'])
#print(ser_obj3.ix['b':4])
image.png
# DataFrame對象
print(df_obj5)
print(df_obj5.ix[1:3,1:3])
print(df_obj5.ix[1:3,'b':'d'])
image.png

Pandas的對齊運算

是數(shù)據(jù)清洗的重要過程,可以按索引對齊進行運算,如果沒對齊的位置則補NaN

Series的對齊運算

1.Series 按行、索引對齊

ser_obj5 = pd.Series(range(10,20),index=range(10))
ser_obj6 = pd.Series(range(15,20),index=range(5))
print(ser_obj5)
print(ser_obj6)
image.png
ser_obj5 + ser_obj6
image.png
print(ser_obj5.add(ser_obj6))
image.png
print(ser_obj5.add(ser_obj6,fill_value=0))
image.png

DataFrame的對齊運算

DataFrame做對齊運算時,未對齊數(shù)據(jù)可以通過fill_value來指定數(shù)據(jù)做對齊運算
add,sub,mul,div,加減乘除

df_obj6 = pd.DataFrame(np.ones((2,2)),columns=['a','b'])
print(df_obj6)
df_obj7=pd.DataFrame(np.ones((5,4)),columns=['a','b','c','d'])
print(df_obj7)
image.png
df_obj6 + df_obj7
image.png
df_obj6.add(df_obj7,fill_value=0)
image.png
df_obj6.add(df_obj7,fill_value=1)
image.png
df_obj8 = pd.DataFrame(np.random.randn(5,4)-1)
print(df_obj8)
image.png

Pandas的函數(shù)應(yīng)用

1.可以直接使用numpy的函數(shù)
在numpy里,可以對數(shù)組里的每一個元素進行操作的函數(shù)稱為ufunc 通用函數(shù)(universal function)
在Pandas里可以直接使用Numpy的ufunc

print(df_obj8.abs())

image.png

2.通過apply將函數(shù)應(yīng)用到列或行上

f = lambda x:x.max()
print(df_obj8.apply(f))

image.png

3.通過applymap將函數(shù)應(yīng)用到每個數(shù)據(jù)上,只用于DataFrame

# 取DataFrame對象中每一個浮點數(shù)小數(shù)點后兩位
print(df_obj8.applymap(lambda x:"%.2f"%x))
image.png

ps:
DataFrame對象可以用apply()和applymap()
apply()應(yīng)用于行,列,可以通過axis來指定
Series對象只能用apply ,效果等于Pyton的map()
ser_obj.map(func)
ser_obj.apply(func)

4.排序

分為按索引排序和按值排序
4.1索引排序
sort_index()
排序默認為升序排序,asscending=False為降序排序

# Series 
ser_obj8 = pd.Series(range(10,15),index=np.random.randint(5,size=5))
print(ser_obj8)
image.png
sorted_obj = ser_obj8.sort_index()
print(sorted_obj)
print(type(sorted_obj))
image.png
print(ser_obj8.sort_index(ascending=False))
image.png

對DataFrame操作時注意軸方向,默認列,axis = 1 為行

df_obj9 = pd.DataFrame(np.random.randn(3,5),index=np.random.randint(3,size=3),columns=np.random.randint(5,size=5))
print(df_obj9)
image.png
# 默認情況下 ,按行索引排序,升序
print(df_obj9.sort_index())
image.png
print(df_obj9.sort_index(axis=1,ascending=False))

image.png

4.2按值排序
sort_values(by='column name')
根據(jù)某個唯一的列名進行排序,如果有其他相同列名則報錯
series 對象的按值排序

# series 對象的按值排序
ser_obj9 = pd.Series(np.random.randint(10,20,size=10))
print(ser_obj9)
image.png
# 默認 升序
print(ser_obj9.sort_values())
image.png
# ascending = false 降序
print(ser_obj9.sort_values(ascending=False))

image.png

Dataframe對象按值排序

df_obj10 = pd.DataFrame(np.random.randn(3,5),index=np.random.randint(3,size=3),columns=np.random.randint(5,size=5))
print(df_obj10)
image.png
# 默認的按列排序
print(df_obj10.sort_values(by=0))
image.png
print(df_obj10.sort_values(by=1,axis=1,ascending=False))

image.png

4.3處理缺失數(shù)據(jù)

df_obj11 = pd.DataFrame(
    [[1,2,3,np.nan],
    [4,5,np.nan,6],
    [7,8,9,np.nan],
    list(range(4))]
)
print(df_obj11)
image.png
print(df_obj11.isnull())

image.png

丟棄

print(df_obj11.dropna())
print(df_obj11.dropna(axis=1))
image.png

填充

print(df_obj11.fillna(3.14))
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容