我尝试了以下操作并出现错误:>>> import pandas as pd>>> df = pd.DataFrame([[0,0],[2,2]])>>> df 0 10 0 01 2 2>>> y = [[0,0],[2,2],[3,3]]>>> df["s","d"] = yTraceback (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"]] = yTraceback (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 回答
慕的地10843
TA贡献1785条经验 获得超8个赞
您无法在尝试时直接执行此操作,但这是一种解决方法:
import pandas as pd
df = pd.DataFrame([[0,0],[2,2]])
y = [[0,0],[2,2]]
df["s"], df["d"] = [i[0] for i in y], [i[1] for i in y]
你有一些问题,其中之一df['s', 'd']是不正确的索引,你需要df[['s', 'd']]- 但你也不能直接从列表分配给它。
你也不能分配比索引长的任何东西,所以你y = [[0,0],[2,2],[3,3]]太长了。
添加回答
举报
0/150
提交
取消