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

相关文章:

javascript - Flask:单击按钮下载 csv 文件

python - Python 的 importlib 有什么意义?

python - 如何防止fabric form等待进程返回

python - 将 Flightradar24 API 转换为 pandas 数据帧

python - Pandas 重采样功能不适用于 DateTimeIndex

javascript - 使用 Babel CLI 提取器提取 Javascript gettext 消息

python - 从 DataFrame 中的标签获取列号

python - Pandas : balancing data

python - Pandas 按行组应用卷积

Python。从 Pandas 列中提取字符串的最后一位