我需要将列'FocusColumn'
的 NaN 值更改为空列表。
我尝试这样做:
df['FocusColumn'].fillna([],inplace=True)
但它给我抛出了以下错误:
337 if validate_scalar_dict_value and isinstance(value, (list, tuple)):
338 raise TypeError(
339 '"value" parameter must be a scalar or dict, but
340 f'you passed a "{type(value).__name__}"'
341 )
TypeError: "value" parameter must be a scalar or dict, but you passed a "list"
正确的方法是什么?
看起来您可以通过向Series.fillna
提供字典来解决此问题。
>>> df
FocusColumn
0 NaN
1 1.0
2 NaN
>>> df['FocusColumn'].fillna({i: [] for i in df.index})
0 []
1 1
2 []
Name: FocusColumn, dtype: object
笔记:
- 令人惊讶的是,这仅适用于
Series.fillna
. - 对于缺少值很少的大型序列,这可能会创建不合理的一次性空列表。
- 使用
pandas
1.0.5 进行测试。
您可以尝试以下操作:
import pandas as pd
import numpy as np
df = pd.DataFrame({'FocusColumn': [1, 2, 3, 4, np.NaN, np.NaN, np.NaN, np.NaN], 'Column1': [1, 2, 3, 4, 5, 6, 7, 8], 'Column2': [7, 8, 6, 5, 7, 8, 5, 4]})
df['FocusColumn'] = df['FocusColumn'].apply(lambda x: [] if np.isnan(x) else x)
print(df)
输出:
FocusColumn Column1 Column2
0 1 1 7
1 2 2 8
2 3 3 6
3 4 4 5
4 [] 5 7
5 [] 6 8
6 [] 7 5
7 [] 8 4