【问题标题】:Replace pandas dataframe columns with another dataframe based on specific column根据特定列将熊猫数据框列替换为另一个数据框
【发布时间】:2021-01-18 15:29:12
【问题描述】:

我有两个包含许多列 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


【问题讨论】:

  • 您可以只连接两个数据框并删除第一个数据框列。

标签: python pandas dataframe


【解决方案1】:

我认为我能够理清思路,并希望找到适合您的解决方案。

试试这个,你可以使用combine_first得到答案,并做一些调整:

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

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

【讨论】:

    【解决方案2】:

    你需要合并:

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

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

    【讨论】:

    • 这不会引发错误吗?当我们做 df1['time'] 我们会得到一个系列,然后调用“合并”这是一个数据框属性
    • 合并的问题是它创建了那些带有 _x、_y 后缀的额外列
    • 没问题。帮助您区分相似列名的来源
    • 不幸的是,这对我来说是个问题:(,那些后缀会在程序的其他部分产生问题
    【解决方案3】:

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

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

    【讨论】:

    • 不起作用,它将从 df1 (1.1, 1.1, 1.1 ) 中删除重复的时间值,并且还会添加 df1 中不存在的值(例如,它将添加 1.6 不存在的时间在 df1)
    • @Tenshi 你看懂我贴的代码了吗?我看起来好像你不会。
    • 欢迎您使用我在问题中发布的输入数据尝试您的代码,您会发现它不会给出预期的结果
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2018-08-03
    • 2016-08-09
    • 1970-01-01
    • 2020-10-21
    • 2021-06-25
    相关资源
    最近更新 更多