python - 在 Pandas Dataframe 中计算 NaN 但忽略了领先的

标签 python pandas

我想计算数据框中包含的每一列的 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.countNaN 的缺失值减去非 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/

相关文章:

python - Sklearn 单变量选择 : Features are Constant

python - pandas dataframe 按不均匀时间戳分组

Python Pandas : Convert a date string to milliseconds since epoch and back to date string?

python - 试图绘制的 Pandas 类型错误

python - 在 Pandas 的列上应用 lambda

python - 如何根据条件为每个 id 分配二进制值

python - Django 模型,其中字段基于另一个字段,除非另有说明

python - 使用 Boto3 嵌套键获取 S3 中文件的完整路径

python - Pytorch 的 nn.TransformerEncoder "src_key_padding_mask"未按预期运行

python - 属性错误 : 'PosixPath' object has no attribute 'path'