我想计算数据框中包含的每一列的 NaN,但忽略前导 NaN。
所以我的数据框具有以下结构:
import pandas as pd
import numpy as np
df=pd.DataFrame({'Date':
pd.date_range(pd.datetime.today().strftime("%m/%d/%Y"),periods=10).tolist(),
'Col1': [np.nan,np.nan,np.nan,4,5,6,7,np.nan,np.nan,np.nan],
'Col2': [np.nan,np.nan,np.nan,4,5,6,7,8,9,np.nan],
'Col3': [np.nan,2,3,4,np.nan,6,7,8,9,np.nan] })
df
Date Col1 Col2 Col3
0 2019-08-16 NaN NaN NaN
1 2019-08-17 NaN NaN 2.0
2 2019-08-18 NaN NaN 3.0
3 2019-08-19 4.0 4.0 4.0
4 2019-08-20 5.0 5.0 NaN
5 2019-08-21 6.0 6.0 6.0
6 2019-08-22 7.0 7.0 7.0
7 2019-08-23 NaN 8.0 8.0
8 2019-08-24 NaN 9.0 9.0
9 2019-08-25 NaN NaN NaN
期望的输出应该是一个数据帧,某物。喜欢:
Col1 Col2 Col3
3 1 2
最佳答案
首先过滤所有没有first by DataFrame.iloc
的列然后用 DataFrame.count
将 NaN
的缺失值减去非 nans 值计算所有非 nans 值:
df1 = df.iloc[:, 1:]
a = df1.ffill().count() - df1.count()
或者:
df1 = df.iloc[:, 1:]
a = df1.isna().sum() - df1.ffill().isna().sum()
或者:
df1 = df.iloc[:, 1:]
a = df1.mask(df1.ffill().isna(), 1).isna().sum()
print (a)
Col1 3
Col2 1
Col3 2
dtype: int64
最后如果需要一行DataFrame:
df1 = a.to_frame(0).T
print (df1)
Col1 Col2 Col3
0 3 1 2
关于python - 在 Pandas Dataframe 中计算 NaN 但忽略了领先的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57519632/