我想通过遍历熊猫的每一行来添加带有列表的新列
我尝试使用df.at,但它给了我一个值错误
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
for index, row in df.iterrows():
df.at[index,'new_col'] = ['m','n']
实际结果:
Traceback (most recent call last):
File "D:/Projects/fasttextproj/test.py", line 10, in
df.at[index,'new_col'] = ['m','n']
File "D:\Projects\fasttext\lib\site-packages\pandas\core\indexing.py", line 2287, in __setitem__
self.obj._set_value(*key, takeable=self._takeable)
File "D:\Projects\fasttext\lib\site-packages\pandas\core\frame.py", line 2823, in _set_value
self.loc[index, col] = value
File "D:\Projects\fasttext\lib\site-packages\pandas\core\indexing.py", line 190, in __setitem__
self._setitem_with_indexer(indexer, value)
File "D:\Projects\fasttext\lib\site-packages\pandas\core\indexing.py", line 366, in _setitem_with_indexer
self._setitem_with_indexer(new_indexer, value)
File "D:\Projects\fasttext\lib\site-packages\pandas\core\indexing.py", line 611, in _setitem_with_indexer
raise ValueError('Must have equal len keys and value '
ValueError: Must have equal len keys and value when setting with an iterable
答案 0 :(得分:0)
尝试:
df['new_col'] = [['m', 'n']] * df.shape[0]
答案 1 :(得分:0)
您还可以使用:
df['new_col'] = [['m', 'n'] for i in df.index]
或者
df =df.assign(new_col = [['m', 'n'] for i in df.index])