python - 将 2D 列表分配给 2 个 Dataframe 列 Pandas

标签 python python-3.x pandas

我尝试了以下方法并收到错误:

>>> 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"

让我知道如何同时使用 2D 数组创建 2 列。

最佳答案

使用DataFrame构造函数并分配给嵌套列表:

df = pd.DataFrame([[0,0],[2,2]])

y = [[0,0],[2,2]]

df[["s","d"]] = pd.DataFrame(y)
print (df)
   0  1  s  d
0  0  0  0  0
1  2  2  2  2

另一个解决方案是创建新的 DataFramejoin原文:

df = df.join(pd.DataFrame(y, columns=['s','d'], index=df.index))

如果您想添加多列:

df = pd.DataFrame([[0,0],[2,2]])

y = [[0,0],[2,2],[3,3]]

df[["s","d","e"]] = pd.DataFrame(np.array(y).T)
print (df)
   0  1  s  d  e
0  0  0  0  2  3
1  2  2  0  2  3

z = [[0,0,3],[2,2,3]]
df[["s","d","e"]] = pd.DataFrame(z)
print (df)
   0  1  s  d  e
0  0  0  0  0  3
1  2  2  2  2  3

如果需要将 2 个新列附加到 3 行 DataFrame:

df = pd.DataFrame([[0,0],[2,2],[4,4]])

y = [[0,0],[2,2],[3,3]]

df[["s","d"]] = pd.DataFrame(y)
print (df)

   0  1  s  d
0  0  0  0  0
1  2  2  2  2
2  4  4  3  3

否则获取缺失值:

df = pd.DataFrame([[0,0],[2,2]])

y = [[0,0],[2,2],[3,3]]

df = df.join(pd.DataFrame(y, columns=['s','d']), how='outer')
print (df)
     0    1  s  d
0  0.0  0.0  0  0
1  2.0  2.0  2  2
2  NaN  NaN  3  3

关于python - 将 2D 列表分配给 2 个 Dataframe 列 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593052/

相关文章:

python - 如何用python求解非线性DE的9方程组?

python 在打印函数后留下一行

python-3.x - pandas如何将二维数据框转换为一维数据框

python - 为什么for循环在python中退出 ""(空字符串)?

python - 使用 Python 对数据框进行分组

python - 将函数应用于 Pandas 数据框

python - 将多个 if 语句放入 python pandas 的一个 if 语句中

python - 在 Django 模型中自动对 ManyToMany 字段进行排序

python在不同的执行中设置散列

python - kedro 中是否有 IO 功能来存储训练好的模型?