如何在 pandas 的数据框列中分配列表值?

4
我想创建一个新的df列来保存列表值。
def add_list_values(row): # row parameter is needed but not in this sample code
    list_val = [1, 'OKOKOK', 2123]
    return list_val

df['new_col'] = df.apply(add_list_values, axis=1)

Error: ValueError: Shape of passed values is (91, 4), indices imply (91, 2)

当我仅仅将一个包含列表值的列进行赋值测试时,我得到了类似的错误。
df['new_col2'] = [1, 'OKOKOK', 2123]

ValueError: Length of values does not match length of index

你期望的 'new_col2' 列的值是什么?样本列表为 [1, 'OKOKOK', 2123]。根据错误信息,似乎行数不匹配。 - TechWizard
1
[1, 'OKOKOK', 2123] has a length of 3, in your example the length of df appears to be longer than that. To assign the list [1, 'OKOKOK', 2123] to every row in the df do something like df['new_col2'] = [[1, 'OKOKOK', 2123] for x in df.index] - jtweeder
1个回答

6
如果我理解正确的话,尝试使用以下代码替换导致错误的那一行:
df['c']=[[1, 'OKOKOK', 2123]]*len(df)
df
Out[148]: 
   a  b                  c
0  1  1  [1, OKOKOK, 2123]
1  3  4  [1, OKOKOK, 2123]
2  3  4  [1, OKOKOK, 2123]

1
请问您能详细说明如何将此应用于在df.apply中使用的函数吗? - KubiK888
// 我假设这段代码将替换原问题中的 df['new_col2'] = [1, 'OKOKOK', 2123] - Nathan Basanese
我尝试了,但出现了错误 - ValueError: Wrong number of items passed 2, placement implies 1。 - KubiK888

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接