我需要为 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