如何将列中的某些单元格设置为列表列表中的列表,其中列表列表的长度与单元格数相同?
当运行我尝试的部分时,我得到以下错误:
ValueError:使用ndarray
下面用desired
明确定义的我想要的DataFrame如下所示:
include array
0 True [1, 2]
1 False NaN
2 False NaN
3 True [3, 4]
4 False NaN
尝试的代码:
import pandas as pd
# This is what I tried
a = pd.DataFrame({'include': [True, False, False, True, False]})
a.loc[a['include'], 'array'] = [[1, 2], [3, 4]]
# This is what I want
desired = pd.DataFrame({'include': [True, False, False, True, False],
'array': [[1, 2], np.nan, np.nan, [3, 4], np.nan]})
不完全确定您想做什么,但您可以将其转换为pandas.Series
并对所有索引进行签名:
a.loc[a['include'], 'array'] = pd.Series([[1, 2], [3, 4]], index=[0, 3])
print(a)
include array
0 True [1, 2]
1 False NaN
2 False NaN
3 True [3, 4]
4 False NaN
要保持索引的分配是通用的,而不是硬编码的,请使用:
a.loc[a['include'], 'array'] = pd.Series([[1, 2], [3, 4]], a[a['include']].index)