gpt4 book ai didi

python - 合并 2 个 Pandas DataFrame,如果索引匹配,则将一条记录替换为另一条记录

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

我想合并两个 Pandas DataFrame,但在索引匹配的任何地方我只想合并来自特定 df 的行。

如果我有

df1
A B
type model
apple v1 10 xyz
orange v2 11 pqs

df2
A B
type model
apple v3 11 xyz
grape v4 12 def

我会得到

df3 
A B
type model
apple v1 10 xyz
orange v2 11 pqs
grape v4 12 def

因为 df1.ix['apple'] 优先于 df2.ix['apple'],并且 orange葡萄是独一无二的。

我一直在尝试进行一些索引比较,但是 df2.drop(df1.index[[0]]) 只是删除了 df2 的全部内容.

两个数据框都是多索引的,结构相似,创建者:

pd.read_csv(..., index_col=[3, 1])

这会导致这样的索引:

MultiIndex(
levels=[[u'apple', u'orange', u'grape', ...], [u'v1', u'v2', u'v3', ... ]],
labels=[[0, 1, 2, 3, 4, 6, 7, 8, 9, 10, ...]],
names=[u'type', u'model']
)

最佳答案

这就是DataFrame.combine_first()用于:

import pandas as pd

df1 = pd.DataFrame({'A': [10, 11], 'B': ['xyz', 'pqs']}, index=['apple', 'orange'])
df2 = pd.DataFrame({'A': [11, 12], 'B': ['xyz', 'def']}, index=['apple', 'grape'])

df3 = df1.combine_first(df2)

产量

df3
A B
apple 10.0 xyz
grape 12.0 def
orange 11.0 pqs

编辑:在我发布上面的答案后,问题进行了实质性修改——将 model 级别添加到索引中,有效地将其变成了 MultiIndex。

import pandas as pd

# Create the df1 in the question
df1 = pd.DataFrame({'model': ['v1', 'v2'], 'A': [10, 11], 'B': ['xyz', 'pqs']},
index=['apple', 'orange'])
df1.index.name = 'type'
df1.set_index('model', append=True, inplace=True)

# Create the df2 in the question
df2 = pd.DataFrame({'model': ['v3', 'v4'], 'A': [11, 12], 'B': ['xyz', 'def']},
index=['apple', 'grape'])
df2.index.name = 'type'
df2.set_index('model', append=True, inplace=True)

# Solution: remove the `model` from the index and apply the above
# technique. Restore it to the index at the end if you want.
df1.reset_index(level=1, inplace=True)
df2.reset_index(level=1, inplace=True)
df3 = df1.combine_first(df2).set_index('model', append=True)

结果:

df3
A B
type model
apple v1 10.0 xyz
grape v4 12.0 def
orange v2 11.0 pqs

关于python - 合并 2 个 Pandas DataFrame,如果索引匹配,则将一条记录替换为另一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38107344/

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