同时合并和连接

问题描述 投票:0回答:1

我有多个数据框,每个数据框代表每月的进度。 我的使命就是带着两个条件一步步加入他们。 所以这里是三个示例数据框,我将尝试解释我想要实现的目标。

import pandas as pd

data_22_3 = {
    'id_number': ['A123', 'B456', 'C789'],
    'company': ['Insurance1', 'Insurance2', 'Insurance3'],
    'type': ['A', 'A', 'C'],
    'Income': [100, 200, 300]
}
df_22_3 = pd.DataFrame(data_22_3)

data_22_4 = {
    'id_number': ['A123', 'B456', 'D012'],
    'company': ['Insurance1', 'Insurance2', 'Insurance1'],
    'type': ['A', 'B', 'B'],
    'Income': [150, 250, 400]
}
df_22_4 = pd.DataFrame(data_22_4)

data_22_5 = {
    'id_number': ['A123', 'C789', 'E034'],
    'company': ['Insurance1', 'Insurance3', 'Insurance5'],
    'type': ['A', 'C', 'B'],
    'Income': [180, 320, 500]
}
df_22_5 = pd.DataFrame(data_22_5)

因此,我们将第一个数据帧作为主数据帧。连接第一个和第二个数据框应如下所示:

如果第二个数据框的

id_number
存在于第一个数据框上,则
Income_2
的新列应添加到第一个数据框作为下个月的收入。由于下一个数据框具有相同的列,因此除“收入”之外的所有列都应被忽略。

如果第一个数据帧中不存在第二个数据帧的

id_number
,则应将整行添加到第一个数据帧中。唯一需要考虑的是将
Income
值放入
Income_2
列,并将 0 放入
Income
列,因为该值属于下个月。

生成的数据帧应该以类似的方法与下一个数据帧连接,依此类推。

即使

Type
Company
等其他列的值存在差异,只要
id_number
相同,就应该取前一个数据框的值。

我可能解释得不够充分,但结果是这样的:

data_all = {
    'id_number': ['A123', 'B456', 'C789', 'D012', 'E034'],
    'company': ['Insurance1', 'Insurance2', 'Insurance3', 'Insurance1', 'Insurance5'],
    'type': ['A', 'A', 'C', 'B', 'B'],
    'Income': [100, 200, 300, 0, 0],
    'Income_2': [150, 250, 0, 400, 0],
    'Income_3': [180, 0, 320, 0, 500]
}

all_df = pd.DataFrame(data_all)
python pandas dataframe merge concatenation
1个回答
0
投票

你可以尝试:

out = pd.concat(
    [
        df_22_3.set_index("id_number"),
        df_22_4.set_index("id_number")[["company", "type", "Income"]].add_suffix("_2"),
        df_22_5.set_index("id_number")[["company", "type", "Income"]].add_suffix("_3"),
    ],
    axis=1,
).reset_index()

out["company"] = out[["company", "company_2", "company_3"]].apply(
    lambda x: x[x[x.notna()].idxmax()], axis=1
)

out["type"] = out[["type", "type_2", "type_3"]].apply(
    lambda x: x[x[x.notna()].idxmax()], axis=1
)

out = out.drop(columns=["type_2", "type_3", "company_2", "company_3"]).fillna(0)

print(out)

打印:

  id_number     company type  Income  Income_2  Income_3
0      A123  Insurance1    A   100.0     150.0     180.0
1      B456  Insurance2    B   200.0     250.0       0.0
2      C789  Insurance3    C   300.0       0.0     320.0
3      D012  Insurance1    B     0.0     400.0       0.0
4      E034  Insurance5    B     0.0       0.0     500.0
© www.soinside.com 2019 - 2024. All rights reserved.