我想为我的pandas列的每个单元分配一些列表。
index= [0,1,2,3]
myvalues = [[43, 35], [37, 3, 29], [34, 90, 102, 23]]
myDF = pd.DataFrame(index=index)
myDF['column'] = [[] for _ in range(len(myDF))]
myDF.loc[[0,3], 'column'] = myvalues[0]
myDF.loc[1, 'column'] = myvalues[1]
myDF.loc[2, 'column'] = myvalues[2]
myDF
column
0 43
1 [37, 3, 29]
2 [34, 90, 102, 23]
3 35
但是我想要myDF.column[0] = myvalues[0] = [43, 35]
和myDF.column[3] = myvalues[0] = [43, 35]
在更复杂的情况下,
infoData['cumCSchool'] = [[] for _ in range(len(infoData))] ## the column I want to change
for i,j in enumerate(df['name']):
tmp = infoData[infoData['name']==j] ## info about a name
some_list = list(tmp.index.values) ## list of the index I want to change
val = list(df['cumCSchool'][i].values)
infoData.loc[[some_list], 'cumCSchool'] = [val]
我遇到了以下错误
"None of [Index([(0, 27, 68, 69, 71, 77, 82, 84, 92, 93, 107, 122, 140, 141, 149, 159, 188, 205, 224, 226, 231, 236, 261, 263, 270, 274, 289, 292, 293, 302, 313, 325, 330, 332, 336, 346, 347, 351, 357, 388, 421, 423, 430, 436, 448, 461, 483, 491, 501, 503, 517, 524, 525, 530, 562, 575, 582, 583, 599, 600, 602, 606, 617, 620, 630, 638, 640, 648, 649, 663, 673, 675, 679, 686, 689, 704, 705, 717, 720)], dtype='object')] are in the [index]"
答案 0 :(得分:1)
只需使用myDF.loc[[0,3], 'column'] = [myvalues[0]]
:
index= [0,1,2,3]
myvalues = [[43, 35], [37, 3, 29], [34, 90, 102, 23]]
myDF = pd.DataFrame(index=index)
myDF['column'] = [[] for _ in range(len(myDF))]
myDF.loc[[0,3], 'column'] = [myvalues[0]]
myDF.loc[1, 'column'] = myvalues[1]
myDF.loc[2, 'column'] = myvalues[2]
myDF
输出:
column
0 [43, 35]
1 [37, 3, 29]
2 [34, 90, 102, 23]
3 [43, 35]