计算 pandas 数据帧行中的非空单元格并将计数添加为列

Count non-empty cells in pandas dataframe rows and add counts as a column

使用 Python,我想计算 pandas 数据框中一行中包含数据 的单元格数量 并在该行最左边的单元格中记录计数

要计算每行中缺失数据的单元格数量,您可能需要这样做:

df.apply(lambda x: x.isnull().sum(), axis='columns')

df 替换为您的数据框的标签。

您可以创建一个新列并使用类似以下内容将计数写入其中:

df['MISSING'] = df.apply(lambda x: x.isnull().sum(), axis='columns')

该列将创建在数据框的末尾(最右边)。

您可以像这样移动您的列:

df = df[['Count', 'M', 'A', 'B', 'C']]

更新

我想知道您丢失的单元格是否实际上是空字符串而不是 NaN 值。你可否确认?我将您的屏幕截图复制到 Excel 工作簿中。我的完整代码如下:

df = pd.read_excel('count.xlsx', na_values=['', ' '])
df.head() # You should see NaN for empty cells
df['M']=df.apply(lambda x: x.isnull().sum(), axis='columns')
df.head() # Column M should report the values: first row: 0, second row: 1, third row: 2
df = df[['Count', 'M', 'A', 'B', 'C']]
df.head() # Column order should be Count, M, A, B, C

注意 pd.read_excel 方法中的 na_values 参数。