如何将DataFrame中的空列表转换为NaN?

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

我得到了以下数据框:

enter image description here

我合并了两个不同的列表。 Standstillreason的单元格中可能包含带有内容的列表,或者可能已经是“ NaN”。我的目标是将空列表(如上图所示)也转换为“ NaN”。我是一个初学者,我知道.replace方法。但这似乎不起作用吗?

df.Standstillreason = df.Standstillreason.replace("", np.nan, inplace=True)

我试图用""[]" ""[]"替换"[ ]"。但是,所有这些代码所做的就是用None替换了整个列,甚至是非空单元格。我该怎么做,仅将具有空列表的那些单元格转换为NaN

python pandas numpy dataframe nan
1个回答
0
投票

让我们尝试bool

df.loc[~df.Standstillreason.astype(bool),'Standstillreason']=np.nan

详细信息

s=pd.Series([[],[1]])
s
0     []
1    [1]
dtype: object
s.astype(bool)
0    False
1     True
dtype: bool
© www.soinside.com 2019 - 2024. All rights reserved.