gpt4 book ai didi

python - 从另一个数据框中替换列的值

转载 作者:行者123 更新时间:2023-12-01 00:14:22 25 4
gpt4 key购买 nike

您好,有一个包含 10000 多行的数据框,如下所示 -

df = pd.DataFrame([['110', 'Demand', 2344, 30953], 
['111', 'Supply', 3535, 321312],
['112', 'Supply', 35345, 2324],
['113', 'Demand', 24345, 4542],
['114', 'Supply', 342, 435623]],
columns=['Material', 'Title', '201950', '201951'])
df

Material Title 201950 201951
110 Demand 2344 30953
111 Supply 3535 321312
112 Supply 35345 2324
113 Demand 24345 4542
114 Supply 342 435623

我有另一个大约 4-5 行的小数据框,如下所示 -

extra = pd.DataFrame([['111', 'Supply', 10],
['112', 'Supply', 20],
['114', 'Supply', 30],
['115', 'Supply', 40]],
columns=['Material', 'Title', '201950'])
extra
Material Title 201950
111 Supply 10
112 Supply 20
114 Supply 30
115 Supply 40

我想使用 extra 中的值替换 df201950 中的值,无论 MaterialTitle 匹配,以便生成的数据帧看起来像这样 -

Material    Title   201950  201951
110 Demand 2344 30953
111 Supply 10 321312
112 Supply 20 2324
113 Demand 24345 4542
114 Supply 30 435623

我确实尝试过合并

updated = df.merge(extra, how='left',
on=['Material', 'Title'],
suffixes=('', '_new'))
new = '201950_new'
updated['201950'] = np.where(pd.notnull(updated[new]), updated[new], updated['201950'])
updated.drop(new, axis=1, inplace=True)

这给了我所需的输出。但我正在寻找更有效的解决方案。由于 df 很大,而 extra 只有 4 行。

最佳答案

使用DataFrame.update ,但首先在两个 DataFrame 中通过 MaterialTitle 列创建 MultiIndex:

df = df.set_index(['Material','Title'])
extra = extra.set_index(['Material','Title'])

df.update(extra)
df = df.astype(int).reset_index()
print (df)
Material Title 201950 201951
0 110 Demand 2344 30953
1 111 Supply 10 321312
2 112 Supply 20 2324
3 113 Demand 24345 4542
4 114 Supply 30 435623

关于python - 从另一个数据框中替换列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420315/

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