用基于特定列的另一个数据框替换熊猫数据框列

时间:2021-01-18 15:29:12

标签: python pandas dataframe

我有两个包含许多列 df1、df2 的数据框,我想用 df2 列中时间值相同的数据替换所有 df1 值(时间列除外):

df1:

index time   x y   ......many other columns ( the same as df2)
0       1    1 1
1       1.1  2 2
2       1.1  3 3
3       1.1  4 4
4       1.4  5 5
5       1.5  6 6
6       1.5  7 7


df2:

index time  x   y   ....many other columns (the same as df1)
0       1   10  10
1       1.1 11  11
2       1.2 12  12
3       1.3 13  13
4       1.4 14  14
5       1.5 15  15
6       1.6 16  16



the result for df1 should be:

index time  x   y   ....many other columns 
0       1    10 10
1       1.1  11 11
2       1.1  11 11
3       1.1  11 11
4       1.4  14 14
5       1.5  15 15
6       1.5  15 15


3 个答案:

答案 0 :(得分:0)

您需要合并:

df1 = df1.merge(df2, left_index = True, right_index = True)

那么你需要删除你不需要的列

答案 1 :(得分:0)

编辑:第一次误读了这个问题。这应该会有所帮助:

df1[['time']].merge(df2, on='time')

答案 2 :(得分:0)

我想我能够理清思路,并希望找到对您有用的解决方案。

试试这个,您可以通过使用 combine_first 并进行一些调整来获得答案:

  1. combine_first 填充来自另一个 dataframe 的空值,因此首先您可以用 np.nan 替换所有值('time' 列除外)。请注意,我使用“时间”列作为 index

  2. 由于 combine_first 将返回两个数据帧的并集,因此您可以使用 isin 在最终输出中仅获取来自 df1 的时间值。

import numpy as np
import pandas as pd

df1[df1.columns.difference(['time'])] = np.nan
res = df1.set_index('time').combine_first(df2.set_index('time')).reset_index()
li = [i for i in df1['time'].unique()]

final= res[res['time'].isin(li)]

哪个会让你:

   time     x     y
0   1.0  10.0  10.0
1   1.1  11.0  11.0
2   1.1  11.0  11.0
3   1.1  11.0  11.0
6   1.4  14.0  14.0
7   1.5  15.0  15.0
8   1.5  15.0  15.0

在您的实际数据集上尝试一下,如果有效,请告诉我。