检测包含 list 和 Nan 的列中的空单元格

问题描述 投票:0回答:1

我有一个数据框,其中有一列包括列表和南。我想用 {} 替换所有空列表和 Nan。

我的数据是:

df['c'] = [[l1],[l2]], [], Nan

如果我使用

df['c'].apply(lambda x: {} if pd.isna(x) or len(x)==0 else x[0])

它会回来
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

因为对于 [[l1], [l2]],它将返回 [false, false]
但如果我使用
df['c'].apply(lambda x: {} if pd.isna(x).all() or len(x)==0 else x[0])

对于 Nan 来说,它会返回
'bool' object has no attribute 'all'

python list nan
1个回答
0
投票

我使用

创建了一个示例数据框
df['c'] = [[4,5],[1,2,3]], [], np.nan

# Output
    c
0   [[4, 5], [1, 2, 3]]
1   []
2   NaN

This should work -
df['c'] = df['c'].apply(lambda x: {} if x == [] or x is np.nan else x)
© www.soinside.com 2019 - 2024. All rights reserved.