
24.png
在本篇文章中,我們將深入探討Pandas庫中兩個(gè)重要的數(shù)據(jù)處理功能:處理缺失數(shù)據(jù)和數(shù)據(jù)聚合。
一、處理缺失數(shù)據(jù)
在數(shù)據(jù)處理過程中,經(jīng)常會(huì)遇到數(shù)據(jù)缺失的問題。Pandas為此提供了一些方法來處理缺失數(shù)據(jù)。
1. 檢查缺失數(shù)據(jù)
使用isnull()和notnull()函數(shù),可以檢查DataFrame對(duì)象中的每個(gè)元素是否為空。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df['one'].isnull())
2. 填充缺失數(shù)據(jù)
Pandas提供了一個(gè)fillna()函數(shù),可以使用常數(shù)值或前一個(gè)或后一個(gè)數(shù)據(jù)點(diǎn)來填充空值。
print(df.fillna(0)) # 使用0來填充空值
print(df.fillna(method='pad')) # 使用前一個(gè)數(shù)據(jù)點(diǎn)來填充空值
3. 刪除缺失數(shù)據(jù)
如果你想刪除包含缺失值的行,可以使用dropna()函數(shù)。
print(df.dropna())
二、數(shù)據(jù)聚合
數(shù)據(jù)聚合是數(shù)據(jù)處理的重要步驟,Pandas提供了一個(gè)強(qiáng)大的groupby功能,可以按照一個(gè)或多個(gè)列對(duì)數(shù)據(jù)進(jìn)行分組,然后對(duì)每個(gè)分組應(yīng)用一個(gè)函數(shù)。
import pandas as pd
df = pd.DataFrame({
'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)
})
# 分組并對(duì)每個(gè)分組進(jìn)行求和
print(df.groupby('A').sum())
# 按多個(gè)列進(jìn)行分組形成層次索引,然后執(zhí)行函數(shù)
print(df.groupby(['A', 'B']).mean())
Pandas的數(shù)據(jù)聚合功能非常強(qiáng)大,可以使用各種函數(shù)(如mean、sum、size、count、std、var等)進(jìn)行聚合操作。
通過以上這兩個(gè)方面的深入探討,我們可以看到Pandas在數(shù)據(jù)處理方面的強(qiáng)大能力。在實(shí)際的數(shù)據(jù)分析工作中,適當(dāng)?shù)靥幚砣笔?shù)據(jù)和進(jìn)行數(shù)據(jù)聚合,可以幫助我們更好地理解和解釋數(shù)據(jù)。