【发布时间】:2019-04-23 05:04:10
【问题描述】:
我想创建一个新的 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] 的样本?根据错误,似乎行数不匹配。
-
[1, 'OKOKOK', 2123]的长度为 3,在您的示例中,df的长度似乎比这更长。要将列表[1, 'OKOKOK', 2123]分配给df中的每一行,请执行类似df['new_col2'] = [[1, 'OKOKOK', 2123] for x in df.index]
标签: python-3.x pandas list indexing