简体   繁体   English

Python:如何为熊猫细胞分配值列表?

[英]Python: how assign list of values to pandas cells?

I want to assign to each cell of my pandas column some lists. 我想为我的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

However I would like that myDF.column[0] = myvalues[0] = [43, 35] and myDF.column[3] = myvalues[0] = [43, 35] 但是我希望myDF.column[0] = myvalues[0] = [43, 35] myDF.column[3] = myvalues[0] = [43, 35] myDF.column[0] = myvalues[0] = [43, 35]myDF.column[3] = myvalues[0] = [43, 35]

In a more complex case I do, 在更复杂的情况下,

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]

and I got the following error 我得到了以下错误

"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]"

Just use myDF.loc[[0,3], 'column'] = [myvalues[0]] : 只需使用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

Output: 输出:

              column
0           [43, 35]
1        [37, 3, 29]
2  [34, 90, 102, 23]
3           [43, 35]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM