簡體   English   中英

根據特定列將 pandas dataframe 列替換為另一個 dataframe

[英]Replace pandas dataframe columns with another dataframe based on specific column

我有兩個包含許多列 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


你需要合並:

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

那么您需要刪除不需要的列

編輯:第一次誤讀問題。 這應該有助於:

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

我想我能夠讓我的想法井然有序,並希望能找到一個適合你的解決方案。

試試這個,你可以通過使用combine_first得到你的答案,並做一些調整:

  1. combine_first從另一個dataframe填充 null 值,因此首先您可以用np.nan替換所有值(“時間”列除外)。 請注意,我使用“時間”列作為index

  2. 由於combine_first將返回兩個數據幀的並集,因此您可以使用isin僅從最終 output 中的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

在您的實際數據集上嘗試一下,讓我知道它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM