gpt4 book ai didi

python - 如何使用loop来统计nan的个数

转载 作者:行者123 更新时间:2023-12-01 01:38:12 25 4
gpt4 key购买 nike

csv文件中有很多站,我不知道如何使用循环来统计每个站的nan数量。目前为止我得到的就是这些,一一数一下。有人可以帮我吗,先谢谢你了。

station1= train_df[train_df['station'] == 28079004]
station1 = station1[['date', 'O_3']]
count_nan = len(station1) - station1.count()
print(count_nan)

最佳答案

我认为需要按 station 列创建索引 set_index ,过滤列以检查缺失值并最后按 sum 对其进行计数:

train_df = pd.DataFrame({'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'date':pd.date_range('2015-01-01', periods=6),
'O_3':[np.nan,3,np.nan,9,2,np.nan],
'station':[28079004] * 2 + [28079005] * 4})

print (train_df)
B C date O_3 station
0 4 7 2015-01-01 NaN 28079004
1 5 8 2015-01-02 3.0 28079004
2 4 9 2015-01-03 NaN 28079005
3 5 4 2015-01-04 9.0 28079005
4 5 2 2015-01-05 2.0 28079005
5 4 3 2015-01-06 NaN 28079005

df = train_df.set_index('station')[['date', 'O_3']].isnull().sum(level=0).astype(int)
print (df)
date O_3
station
28079004 0 1
28079005 0 2

另一个解决方案:

df = train_df[['date', 'O_3']].isnull().groupby(train_df['station']).sum().astype(int)
print (df)
date O_3
station
28079004 0 1
28079005 0 2

关于python - 如何使用loop来统计nan的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52184338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com