如何在熊猫 df 列中分配列表值?

Kub*_*888 3 indexing list python-3.x pandas

我想创建一个新的 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)
Run Code Online (Sandbox Code Playgroud)

当我通过简单地分配具有列表值的列进行测试时,我得到了类似的错误。

df['new_col2'] = [1, 'OKOKOK', 2123]

ValueError: Length of values does not match length of index
Run Code Online (Sandbox Code Playgroud)

WeN*_*Ben 5

如果我理解正确,请尝试此操作而不是出现错误的行:

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]
Run Code Online (Sandbox Code Playgroud)