Python 如何在Pandas中向数据帧插入数据帧
我有两个数据帧:Python 如何在Pandas中向数据帧插入数据帧,python,pandas,Python,Pandas,我有两个数据帧: import pandas as pd rep1 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP1',[1.00,23.22,11.12]),('RP1.pacall',["A","B","C"]) ], orient='columns') pg = rep1[["Probe","Gene"]] 产生: In [105]: rep1
import pandas as pd
rep1 = pd.DataFrame.from_items([('Probe', ['x', 'y', 'z']), ('Gene', ['foo', 'bar', 'qux']), ('RP1',[1.00,23.22,11.12]),('RP1.pacall',["A","B","C"]) ], orient='columns')
pg = rep1[["Probe","Gene"]]
产生:
In [105]: rep1
Out[105]:
Probe Gene RP1 RP1.pacall
0 x foo 1.00 A
1 y bar 23.22 B
2 z qux 11.12 C
In [107]: pg
Out[107]:
Probe Gene
0 x foo
1 y bar
2 z qux
然后,我要做的是将pg
插入rep1
,结果是:
Probe Gene RP1 Probe Gene RP1.pacall
0 x foo 1.00 x foo G
1 y bar 23.22 y bar I
2 z qux 18.12 z qux K
我试过了,但失败了:
In [101]: rep1.insert(1,["Probe","Gene"],pg)
TypeError: unhashable type: 'list'
正确的方法是什么?调用并传递paramaxis=1
以按列连接:
In [72]:
pd.concat([rep1,pg], axis=1)
Out[72]:
Probe Gene RP1 RP1.pacall Probe Gene
0 x foo 1.00 A x foo
1 y bar 23.22 B y bar
2 z qux 11.12 C z qux
请注意,执行上述操作将导致一些稍微奇怪但正确的行为:
In [73]:
merged = pd.concat([rep1,pg], axis=1)
merged['Probe']
Out[73]:
Probe Probe
0 x x
1 y y
2 z z
为了实现特定的列排序,您必须对原始df列进行切片并选择其中的一个子集(注意使用double[[]]]
):
在concat、merge或join中没有插入点如何指定插入位置?即在
RP1
之后。注意,还有更多的“RPx-RPx.pacall”对。
In [76]:
pd.concat([rep1[['Probe','Gene','RP1']], pg, rep1[['RP1.pacall']]], axis=1)
Out[76]:
Probe Gene RP1 Probe Gene RP1.pacall
0 x foo 1.00 x foo A
1 y bar 23.22 y bar B
2 z qux 11.12 z qux C