ValueError:使用可迭代设置时必须具有相等的 len 键和值

Nem*_*emo 1 python dataframe python-3.x pandas

当我运行这个玩具代码时

test = pd.DataFrame({'a': [1, 2, 3, 4]})
test['b'] = ''
for i in range(len(test)):
    test['b'].loc[i] = [5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

我有一个警告

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self._setitem_single_block(indexer, value, name)
Run Code Online (Sandbox Code Playgroud)

loc但如果我按照这种方法使用

test = pd.DataFrame({'a': [1, 2, 3, 4]})
test['b'] = ''
for i in range(len(test)):
    test.loc[i, 'b'] = [5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

ValueError: Must have equal len keys and value when setting with an iterable
Run Code Online (Sandbox Code Playgroud)

错误是什么意思?特别是,它指的是哪些键、值和可迭代?

小智 6

你可以使用apply

test['b'] = test['b'].apply(lambda x: [5, 6, 7])
Run Code Online (Sandbox Code Playgroud)

或列表串联(或列表理解):

test['b'] = [[5, 6, 7]] * len(test)
Run Code Online (Sandbox Code Playgroud)

如果必须使用循环,则可以使用at(这是有效的,因为您已"b"通过''最初分配它来设置为 dtype 对象,并且at只要类型匹配,就可以将值分配给单元格):

for i in range(len(test)):
    test.at[i, 'b'] = [5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

输出:

   a          b
0  1  [5, 6, 7]
1  2  [5, 6, 7]
2  3  [5, 6, 7]
3  4  [5, 6, 7]
Run Code Online (Sandbox Code Playgroud)