[英]Replace values in a pandas dataframe from another
我有一個 pandas 數據幀(df1),我需要用另一個數據幀(df2)替換一些 df1 值。 df1 包含從 1998-01-01 到 2002-12-31 的時間序列,df1 包含從 1998-03-01 到 1998-07-31 的時間序列。
我想用 df2 的時間段(即 1998-03-01 到 1998-07-31)的 df2 值替換 df1 值
df1=
date kc
1998-01-01 0
1998-01-02 0
1998-01-03 0
1998-01-04 0
1998-01-05 0
.
.
.
2002-12-30 0
2002-12-31 0
and df2=
date kc
1998-03-01 0.3
1998-03-02 0.35
1998-03-03 0.4
1998-03-04 0.45
1998-03-05 0.4
.
.
.
1998-07-30 0.6
1998-07-31 0.7
其中日期列設置為兩個數據框的索引。 我嘗試了以下方法:
df1.loc["1998-03-01":"1998-07-31","kc"]=df2
但它什么也沒改變,df1 保持不變。
樣品:
print (df1)
kc
Date
1998-01-01 0
1998-02-01 0
1998-03-01 0
1998-03-02 0
1998-03-03 0
2002-12-30 0
1998-12-31 0
print (df2)
kc
date
1998-02-01 0.30
1998-03-01 0.35
1998-03-02 0.40
1998-03-03 0.45
1998-03-04 0.40
2002-07-30 0.60
1998-07-31 0.70
您可以使用Series.combine_first
df1["kc"] = df2['kc'].combine_first(df1['kc'])
print (df1)
kc
Date
1998-01-01 0.00
1998-02-01 0.30
1998-03-01 0.35
1998-03-02 0.40
1998-03-03 0.45
2002-12-30 0.00
1998-12-31 0.00
或Index.isin
通過掩碼獲取新值:
df1.loc[df1.index.isin(df2.index), "kc"]=df2['kc']
print (df1)
kc
Date
1998-01-01 0.00
1998-02-01 0.30
1998-03-01 0.35
1998-03-02 0.40
1998-03-03 0.45
2002-12-30 0.00
1998-12-31 0.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.