我有一个列表a
和DataFramedfdf
我正在尝试将列表添加a
到DataFrame的1个单元格中dfdf
这是我的代码:
import pandas as pd
b = [
['andy', 1, 10],
['bob', 2, 20],
['charlie', 3, 30]
]
dfdf = pd.DataFrame(b)
dfdf.columns = ['Name', 'Number', 'Age']
dfdf['Place'] = ''
dfdf = dfdf.astype(object)
a = [1,2,3]
dfdf.loc[0,'Place'] = a
但是它返回一个错误:
ValueError Traceback (most recent call last)
<ipython-input-134-dcf87d474721> in <module>
1 a = [1,2,3]
----> 2 dfdf.loc[0,'Place'] = a
~\anaconda3\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
690
691 iloc = self if self.name == "iloc" else self.obj.iloc
--> 692 iloc._setitem_with_indexer(indexer, value, self.name)
693
694 def _validate_key(self, key, axis: int):
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value, name)
1633 if take_split_path:
1634 # We have to operate column-wise
-> 1635 self._setitem_with_indexer_split_path(indexer, value, name)
1636 else:
1637 self._setitem_single_block(indexer, value, name)
~\anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer_split_path(self, indexer, value, name)
1686 return self._setitem_with_indexer((pi, info_axis[0]), value[0])
1687
-> 1688 raise ValueError(
1689 "Must have equal len keys and value "
1690 "when setting with an iterable"
ValueError: Must have equal len keys and value when setting with an iterable
我正在尝试像这样添加它:
name number age new
0 Andy 1 10 [1, 2]
1 Bob 2 20 50
2 Charlie 3 30 50
有人可以帮我解决这个问题吗?非常感谢
您的代码工作正常,并返回以下输出,这是正确的,但与您列出的预期输出不同:
Name Number Age Place
0 andy 1 10 [1, 2, 3]
1 bob 2 20
2 charlie 3 30
关键步骤是将类型更改为object,以允许将列表插入现有数据框,但是您已经做好了这一工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句