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

时间:2019-02-08 13:03:49

标签: 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列。

2 个答案:

答案 0 :(得分: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行数据框:

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

答案 1 :(得分:1)

您无法在尝试时直接执行此操作,但这需要一些解决方法:

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]]太长了。