将列添加到Pandas DataFrame不到位

Ale*_*erg 6 pandas

如何将系列作为新列添加到Pandas DataFrame并返回一个新的DataFrame(即不到位).

这有效,但已到位:

A["name"] = s
Run Code Online (Sandbox Code Playgroud)

Zer*_*ero 11

从那时0.16.0起,您可以使用assign-- 返回一个新对象(副本),其中包含除新列之外的所有原始列。

In [483]: A.assign(name=s)
Out[483]:
          0         1  name
0  0.876880  0.915174     0
1  0.644664  0.305387     1
2  0.930093  0.562453     2
3  0.807626  0.498871     3
Run Code Online (Sandbox Code Playgroud)

细节

In [484]: A
Out[484]:
          0         1
0  0.876880  0.915174
1  0.644664  0.305387
2  0.930093  0.562453
3  0.807626  0.498871

In [485]: s
Out[485]:
0    0
1    1
2    2
3    3
dtype: int64
Run Code Online (Sandbox Code Playgroud)


wai*_*kuo 5

不确定是否有更优雅的方式,但这对我有用:

df = pd.concat( [A, pd.DataFrame(s)], axis=1 )
Run Code Online (Sandbox Code Playgroud)