gpt4 book ai didi

python - 合并两个数据框,同时保留某一行

转载 作者:太空宇宙 更新时间:2023-11-03 15:49:08 26 4
gpt4 key购买 nike

我的目标

我想合并两个数据框,同时保留行,row_to_keep

数据框

>>> df

ColumnA Stats
0 Cake 872
1 Cheese Cake 912
2 Egg 62
3 Raspberry Jam 091
4 Bacon 123
5 Bread 425
row_to_keep NaN 999

>>> df1

ColumnB
0 Cake
1 Cheese Cake
3 Raspberry Jam
4 Bacon

我的尝试

new_df = df.merge(df1, left_on="ColumnA", right_on="ColumnB")

>>> new_df

ColumnA Stats ColumnB
0 Cake 872 Cake
1 Cheese Cake 912 Cheese Cake
3 Raspberry Jam 091 Raspberry Jam
4 Bacon 123 Bacon

预期输出

合并按预期工作,但我正在努力寻找一种有效的方法来保留 df 的最后一行。

                ColumnA         Stats
0 Cake 872
1 Cheese Cake 912
3 Raspberry Jam 091
4 Bacon 123
row_to_keep NaN 999

此外,是否有一种方法可以通过使用 'row_to_keep' 而不是 row[number] 来获取此输出?

最佳答案

更新:

In [139]: df[df.ColumnA.isin(df1.ColumnB)].append(df.loc['row_to_keep'])
Out[139]:
ColumnA Stats
0 Cake 872
1 Cheese Cake 912
3 Raspberry Jam 91
4 Bacon 123
row_to_keep NaN 999

旧答案:

这是一种解决方案:

In [126]: df.merge(df1, left_on="ColumnA", right_on="ColumnB").append(df.loc['row_to_keep'])
Out[126]:
ColumnA Stats ColumnB
0 Cake 872 Cake
1 Cheese Cake 912 Cheese Cake
2 Raspberry Jam 91 Raspberry Jam
3 Bacon 123 Bacon
row_to_keep NaN 999 NaN

说明:

df.loc['row_to_keep'] 通过索引值 ('row_to_keep') 选择一行并 DF.append(row) - 将其附加到合并的 DF

但我必须承认,可能还有不那么丑陋的解决方案......

关于python - 合并两个数据框,同时保留某一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41470948/

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