我有两个数据框:
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'
正确的做法是什么?
最佳答案
调用concat
并传递参数 axis = 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 列进行切片并选择其中的一个子集(注意使用双 [[]]
):
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
concat、merge 或 join 本身没有插入点
关于python - 如何将数据框插入 Pandas 中的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318491/