gpt4 book ai didi

python - 与 Pandas 左侧数据框中的覆盖值合并

转载 作者:行者123 更新时间:2023-11-28 20:55:12 29 4
gpt4 key购买 nike

我有两个 DataFrame C 和 D,如下所示:

C
A B
0 AB 1
1 CD 2
2 EF 3

D
A B
1 CD 4
2 GH 5

我必须合并两个数据框,但合并应该覆盖右侧 df 中的值。数据框中的其余行不应更改。

Output
A B
0 AB 1
1 CD 4
2 EF 3
3 GH 5

df 的行顺序不得更改,即 CD 应保留在索引 1 中。我尝试使用外部合并,它处理索引但复制列而不是覆盖。

>>> pd.merge(c,d, how='outer', on='A')
A B_x B_y
0 AB 1.0 NaN
1 CD 2.0 4.0
2 EF 3.0 NaN
3 GH NaN 5.0

基本上 B_y 应该替换 B_x 中的值(仅在值出现的地方)。我正在使用 Python3.7。

最佳答案

您必须替换行以覆盖现有的值。这与删除重复项不同,因为它会更改行的顺序。

Combine DF 将“pkey”作为参数,它是合并应该发生的主要列。

def update_df_row(row=None, col_name="", df=pd.DataFrame(), pkey=""):
try:
match_index = df.loc[df[pkey] == col_name].index[0]
row = df.loc[match_index]
except IndexError:
pass
except Exception as ex:
raise
finally:
return row

def combine_dfs(parent_df, child_df, pkey):

filtered_child_df = child_df[child_df[pkey].isin(parent_df[pkey])]

parent_df[parent_df[pkey].isin(child_df[pkey])] = parent_df[
parent_df[pkey].isin(child_df[pkey])].apply(
lambda row: update_df_row(row, row[pkey], filtered_child_df, pkey), axis=1)

parent_df = pd.concat([parent_df, child_df]).drop_duplicates([pkey])

return parent_df.reset_index(drop=True)

上述代码片段的输出将是:

    A   B
0 AD 1
1 CD 4
2 EF 3
3 GH 5

关于python - 与 Pandas 左侧数据框中的覆盖值合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491638/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com