从合并结果赋值

2024-04-26 21:03:06 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个数据帧,其中一个在概念上是另一个的子集。如何有效地将数据从子集传输到超集?以下是一些数据:

import pandas as pd

sup = pd.DataFrame({'row': [0, 0, 0, 1, 1, 1, 2, 2],
                    'col': [0, 1, 2, 0, 1, 2, 1, 2], 'val': 1.3})
#    col  row  val
# 0    0    0  1.3
# 1    1    0  1.3
# 2    2    0  1.3
# 3    0    1  1.3
# 4    1    1  1.3
# 5    2    1  1.3
# 6    1    2  1.3
# 7    2    2  1.3

sub = pd.DataFrame({'Row': [2, 0, 1], 'Column': [2, 1, 0], 'Value': [1.1, 4.4, 2.4]})
#    Column  Row  Value
# 0       2    2    1.1
# 1       1    0    4.4
# 2       0    1    2.4

我知道我可以有效地merge两个数据帧:

sup.merge(sub, left_on=['row', 'col'], right_on=['Row', 'Column'])
#    col  row  val  Column  Row  Value
# 0    1    0  1.3       1    0    4.4
# 1    0    1  1.3       0    1    2.4
# 2    2    2  1.3       2    2    1.1

但是我如何用那些匹配的值覆盖sup['val']中的值呢?在我的现实世界中,sup大约是40k行,sub只有1k行。你知道吗

本例中的预期结果是:

#    col  row  val
# 0    0    0  1.3
# 1    1    0  4.4
# 2    2    0  1.3
# 3    0    1  2.4
# 4    1    1  1.3
# 5    2    1  1.3
# 6    1    2  1.3
# 7    2    2  1.1

Tags: 数据import概念dataframepandasvalueoncolumn
1条回答
网友
1楼 · 发布于 2024-04-26 21:03:06

使用^{}并使用^{}^{}更改值,也不需要在此处合并:

sub.rename(columns={'Row':'row', 'Column':'col', 'Value':'val'}, inplace=True)
#alternative sub.columns = sup.columns
sub.set_index(['row','col'], inplace=True)
sup.set_index(['row','col'], inplace=True)
sup.loc[sub.index,:] = sub['val']
sup.reset_index(inplace=True)

print(sup)
   row  col  val
0    0    0  1.3
1    0    1  4.4
2    0    2  1.3
3    1    0  2.4
4    1    1  1.3
5    1    2  1.3
6    2    1  1.3
7    2    2  1.1

相关问题 更多 >