pandas 当某些行中有NaN时,如何计算列的长度?

f45qwnt8  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(107)

我有一个Pandas Dataframe 。在列中我有一个列表。但是,有些行是NaN。我想找到每个列表的长度,如果是NaN,我想用0作为长度。

My_column
[1, 2]-> should return 2
[] -> should return 0
NaN -> should return 0

有什么帮助吗?

  • 谢谢-谢谢
ht4b089n

ht4b089n1#

df['column'].str.len().fillna(0).astype(int)
smdncfj3

smdncfj32#

您可以检查项目是否为list

*如果是列表-确定该列表的长度
*如果不是列表(例如np.nan)-则设置为

output = [len(x) if isinstance(x, list) else 0 for x in df['column']]

下面是一个使用您的输入的示例

import pandas as pd
import numpy as np

df = pd.DataFrame({'column': [['a','b'], np.nan, []]})

output = [len(x) if isinstance(x, list) else 0 for x in df['column']]

print(output)

输出:

[2, 0, 0]

相关问题