我尝试了以下方法,并得到了错误:
>>> import pandas as pd
>>> df = pd.DataFrame([[0,0],[2,2]])
>>> df
0 1
0 0 0
1 2 2
>>> y = [[0,0],[2,2],[3,3]]
>>> df["s","d"] = y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 3119, in __setitem__
self._set_item(key, value)
File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 3194, in _set_item
value = self._sanitize_column(key, value)
File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 3391, in _sanitize_column
value = _sanitize_index(value, self.index, copy=False)
File "C:\Python35\lib\site-packages\pandas\core\series.py", line 4001, in _sanitize_index
raise ValueError('Length of values does not match length of ' 'index')
ValueError: Length of values does not match length of index
>>> df[["s","d"]] = y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 3116, in __setitem__
self._setitem_array(key, value)
File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 3142, in _setitem_array
indexer = self.loc._convert_to_indexer(key, axis=1)
File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1327, in _convert_to_indexer
.format(mask=objarr[mask]))
KeyError: "['s' 'd'] not in index"
字符串
让我知道我如何可以创建2列与二维数组同时进行。
2条答案
按热度按时间ghg1uchk1#
使用
DataFrame
构造函数并赋值给嵌套列表:字符串
另一种解决方案是创建新的
DataFrame
和join
到原始:型
如果您想添加多个列:
型
如果需要追加2个新列到3行DataFrame:
型
否则获取缺失值:
型
1qczuiv02#
你不能在尝试的时候直接这样做,但这是一个工作:
字符串
你有几个问题,其中之一是
df['s', 'd']
是不正确的索引,你需要df[['s', 'd']]
-但你也不能直接从列表分配给它。你也不能分配任何比索引更长的东西,所以你的
y = [[0,0],[2,2],[3,3]]
太长了。