ValueError:索引器与 pandas DataFrame 中的系列不兼容

问题描述 投票:0回答:1
  • 蟒蛇:3.11
  • 熊猫:2.2.2

我需要为 df 中的第 4 行分配一个 dict 值:

df = pd.DataFrame({'agg': [None] * 5})
df['agg'] = df['agg'].astype(object)
df.loc[3, 'agg'] = {'mm': 4}

它给出了一个错误:

Traceback (most recent call last):
  File "/home/sirjay/python/ethereum/lib/analyse_30m.py", line 1898, in <module>
    df.loc[3, 'agg'] = {'mm': 4}
    ~~~~~~^^^^^^^^^^
  File "/home/sirjay/miniconda3/envs/eth/lib/python3.11/site-packages/pandas/core/indexing.py", line 911, in __setitem__
    iloc._setitem_with_indexer(indexer, value, self.name)
  File "/home/sirjay/miniconda3/envs/eth/lib/python3.11/site-packages/pandas/core/indexing.py", line 1944, in _setitem_with_indexer
    self._setitem_single_block(indexer, value, name)
  File "/home/sirjay/miniconda3/envs/eth/lib/python3.11/site-packages/pandas/core/indexing.py", line 2189, in _setitem_single_block
    value = self._align_series(indexer, Series(value))
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sirjay/miniconda3/envs/eth/lib/python3.11/site-packages/pandas/core/indexing.py", line 2455, in _align_series
    raise ValueError("Incompatible indexer with Series")
ValueError: Incompatible indexer with Series

如何修复?此选项

df['agg'].loc[3] = {'mm': 4}
有效,但有警告:

Use `df.loc[row_indexer, "col"] = values` instead, to perform the assignment in a single step and ensure this keeps updating the original `df`.

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
python python-3.x pandas dataframe
1个回答
0
投票

您可以使用

df.at

df.at[3, 'agg'] = {'mm': 4}

输出:

         agg
0       None
1       None
2       None
3  {'mm': 4}
4       None

或者,使用布尔索引,如这篇文章中所建议:

m = df.index == 3
df.loc[m, 'agg'] = [{'m': 4}] * m.sum()
© www.soinside.com 2019 - 2024. All rights reserved.