pandas - 使用 Pandas ,如何在变量索引上连接两个表?

标签 pandas merge

有两个表,条目可能有不同的 id 类型。我需要根据 df1 的 id_type 和 df2 的正确列连接两个表。问题的背景,id是金融界的证券id,id类型可能是CUSIP、ISIN、RIC等。

print(df1)
   id id_type  value
0  11  type_A    0.1
1  22  type_B    0.2
2  13  type_A    0.3

print(df2)
  type_A type_B type_C
0     11     21     xx
1     12     22     yy
2     13     23     zz
所需的输出是
  type_A type_B type_C  value
0     11     21     xx    0.1
1     12     22     yy    0.2
2     13     23     zz    0.3

最佳答案

这是一种替代方法,可以推广到许多安全类型(CUSIP、ISIN、RIC、SEDOL 等)。
一、创建df1df2沿着原始示例的路线:

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'sec_id': [11, 22, 33],
                    'sec_id_type': ['CUSIP', 'ISIN', 'RIC'], 
                    'value': [100, 200, 300]})

df2 = pd.DataFrame({'CUSIP': [11, 21, 31],
                    'ISIN': [21, 22, 23],
                    'RIC': [31, 32, 33],
                    'SEDOL': [41, 42, 43]})
二、创建中间数据框x1 .我们将第一列用于一个连接,第二和第三列用于不同的连接:
index = [idx for idx in df2.index for _ in df2.columns]
sec_id_types = df2.columns.to_list() * df2.shape[0]
sec_ids = df2.values.ravel()

data = [
    (idx, sec_id_type, sec_id)
    for idx, sec_id_type, sec_id in zip(index, sec_id_types, sec_ids)
]

x1 = pd.DataFrame.from_records(data, columns=['index', 'sec_id_type', 'sec_id'])
加入 df1x1df1 中提取值:
x2 = (x1.merge(df1, on=['sec_id_type', 'sec_id'], how='left')
      .dropna()
      .set_index('index'))
最后加入df2x1 (从上一步)得到最终结果
print(df2.merge(x2, left_index=True, right_index=True, how='left'))

   CUSIP  ISIN  RIC  SEDOL sec_id_type  sec_id  value
0     11    21   31     41       CUSIP      11  100.0
1     21    22   32     42        ISIN      22  200.0
2     31    23   33     43         RIC      33  300.0
栏目 sec_id_typesec_id显示连接按预期工作。

关于pandas - 使用 Pandas ,如何在变量索引上连接两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62841858/

相关文章:

git - 使用和 merge 外部 Git 存储库的最佳实践

java - 合并两个数组列表的最快方法

r - 在 R 中使用条件进行内部连接

merge - 有没有办法使用 Cypher 在 Neo4j 中添加具有属性的多个节点

python - 如何在 Pandas 中附加两个或多个数据框并进行一些分析

python - 根据时间列的内容分离 Pandas 数据框

python - 合并具有偏移量的数据帧行(同一天生成但具有不同的时间戳)

Python Reindex 生成 Nan

python - 如何对列值在一定范围内的两个数据框进行外部合并?

python - 合并几个 Python 字典