簡體   English   中英

ValueError:使用可迭代設置時必須具有相等的 len 鍵和值

[英]ValueError: Must have equal len keys and value when setting with an iterable

當我運行這個玩具代碼時

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

我有一個警告

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)

但是如果我按照這種方法使用loc

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

我有一個錯誤

ValueError: Must have equal len keys and value when setting with an iterable

錯誤是什么意思? 特別是它指的是什么鍵、值和可迭代?

您可以使用apply

test['b'] = test['b'].apply(lambda x: [5,6,7])

或列表連接(或列表理解):

test['b'] = [[5,6,7]] * len(test)

如果您必須使用循環,您可以使用at (這有效,因為您已將"b"設置為 dtype 對象,方法是最初使用''分配它,並且只要類型匹配, at可以將值分配給單元格):

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

輸出:

   a          b
0  1  [5, 6, 7]
1  2  [5, 6, 7]
2  3  [5, 6, 7]
3  4  [5, 6, 7]

發生這種情況是因為在第二段代碼中,您嘗試根據索引號而不是列名來設置值。

如果你這樣做:

for i in range(len(test)):
    print(test.loc[i])

這給了你:

a    1
b     
Name: 0, dtype: object
a    2
b     
Name: 1, dtype: object
a    3
b     
Name: 2, dtype: object
a    4
b     
Name: 3, dtype: object

這意味着使用 loc 和 i 變量,您在索引上按行訪問它,這就是為什么您會收到 mismatch len 錯誤。

要克服此警告,請使用loc專門導航到該列:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM