Python 如何将屏蔽数据框列设置为列表列

Python 如何将屏蔽数据框列设置为列表列,python,pandas,dataframe,Python,Pandas,Dataframe,如何从列表列表中将列中的某些单元格设置为列表,列表列表的长度与单元格数相同 运行我尝试的部分时,出现以下错误: ValueError:在使用 恩达雷 下面用desired明确定义的我想要的数据帧如下所示: include array 0 True [1, 2] 1 False NaN 2 False NaN 3 True [3, 4] 4 False NaN 已尝试的代码: 将熊猫作为pd导入 #这就是我试过的 a=pd.

如何从列表列表中将列中的某些单元格设置为列表,列表列表的长度与单元格数相同

运行我尝试的部分时,出现以下错误:

ValueError:在使用 恩达雷

下面用
desired
明确定义的我想要的数据帧如下所示:

   include   array
0     True  [1, 2]
1    False     NaN
2    False     NaN
3     True  [3, 4]
4    False     NaN
已尝试的代码:

将熊猫作为pd导入
#这就是我试过的
a=pd.DataFrame({'include':[True,False,False,True,False]})
a、 loc[a['include'],'array']=[1,2],[3,4]]
#这就是我想要的
所需=pd.DataFrame({'include':[True,False,False,True,False],
'数组':[[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)

不完全确定您想要做什么,但您可以将其转换为一个
pandas.Series
,并对索引进行allign:

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)