gpt4 book ai didi

python - 计算行级 Pandas 数据框中空单元格的数量并相应地创建一列

转载 作者:行者123 更新时间:2023-12-02 03:45:47 24 4
gpt4 key购买 nike

我有一个像这样的空单元格的数据框:

  Col1       Col2      Col3       Col4        Col5       
A B C
G
E R P
J
C K T

我想创建一个额外的列,其中包含每行中空单元格的数量,因此预期的输出如下:

 ID     Col1       Col2      Col3       Col4        Col5      No_Of_Empty     
1 A B C 2
2 G 3
3 E R P 2
4 J 3
5 C K T 3

这是我尝试过的:

df['No_Of_Des'] = df.iloc[:,1::].apply(lambda x: sum(x==' '), axis = 1)

我得到的输出与预期的不一样,我不确定这里出了什么问题?

最佳答案

来源 DF:

In [168]: df
Out[168]:
Col1 Col2 Col3 Col4 Col5
0 A B C
1 G
2 E R P
3 J
4 C K T

演示:

In [170]: df.iloc[:, 1:].eq("")
Out[170]:
Col2 Col3 Col4 Col5
0 True False True False
1 True True False True
2 False True True False
3 True False True True
4 False True True False

In [171]: df.iloc[:, 1:].eq("").sum(axis=1)
Out[171]:
0 2
1 3
2 2
3 3
4 2
dtype: int64

In [172]: df['No_Of_Empty'] = df.iloc[:, 1:].eq("").sum(axis=1)

In [173]: df
Out[173]:
Col1 Col2 Col3 Col4 Col5 No_Of_Empty
0 A B C 2
1 G 3
2 E R P 2
3 J 3
4 C K T 2

关于python - 计算行级 Pandas 数据框中空单元格的数量并相应地创建一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46814687/

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