[英]Replace values in a pandas dataframe from another
I have a pandas data frame(df1) and I need to replace some of the df1 values with another data frame (df2).我有一个 pandas 数据帧(df1),我需要用另一个数据帧(df2)替换一些 df1 值。 the df1 contains a time series from 1998-01-01 to 2002-12-31 and df1 contains time series from 1998-03-01 to 1998-07-31.
df1 包含从 1998-01-01 到 2002-12-31 的时间序列,df1 包含从 1998-03-01 到 1998-07-31 的时间序列。
I want to replace the df1 values with df2 values for the time period of df2 (ie 1998-03-01 to 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
Where the date column is set index for both of the dataframes.其中日期列设置为两个数据框的索引。 I tried the following:
我尝试了以下方法:
df1.loc["1998-03-01":"1998-07-31","kc"]=df2
But it changes nothing, df1 remains same.但它什么也没改变,df1 保持不变。
Samples:样品:
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
You can use Series.combine_first
您可以使用
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
Or Index.isin
for new values by mask:或
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.