繁体   English   中英

根据日期索引上的df1更新df2中的列

[英]Update columns in df2 based on df1 on index of date

我想要一个数据帧df2 ,其中将包含df1中的值。 两个数据框都有日期索引。 两个数据框包含相同的列。 如果df1中存在df2的索引,我只想更新df2的列。

DF1

Symbol          K1     K2       K3   
Date                                      
2011-01-10     0.0     0.0     0.0    
2011-01-13 -1500.0     0.0  4000.0    
2011-01-26     0.0  1000.0     0.0  

DF2

                K1     K2       K3   

2011-01-10     0.0     0.0     0.0
2011-01-11     0.0     0.0     0.0      
2011-01-26     0.0     0.0     0.0   

期望的输出

                K1     K2       K3     

2011-01-10     0.0     0.0     0.0    
2011-01-11     0.0     0.0     0.0   
2011-01-26     0.0  1000.0     0.0  

我试过了

df2 = df2.join(df1, on=df1.index, how='left')

但是收到了这个错误;

引发KeyError('%s not in index'%objarr [mask])KeyError:“ Index([u'2011-01-10',u'2011-01-13',u'2011-01-26',u '2011-02-02',\\ n

任何帮助都超过了欢迎。

谢谢

在索引上找到公共交集,然后使用combine_first

df = df.loc[df.index.intersection(df2.index)].combine_first(df2)

print(df)
Symbol       K1      K2   K3
2011-01-10  0.0     0.0  0.0
2011-01-11  0.0     0.0  0.0
2011-01-26  0.0  1000.0  0.0

细节

idx = df.index.intersection(df2.index)
print(idx)
Index(['2011-01-10', '2011-01-26'], dtype='object')

print(df.loc[idx])
Symbol       K1      K2   K3
2011-01-10  0.0     0.0  0.0
2011-01-26  0.0  1000.0  0.0

您可以尝试合并索引:

df3 =df1.merge(df2, left_index=True, right_index=True, suffixes=("","_"), how='right')
df3= df3.drop(['K1_', 'K2_', 'K3_'], axis=1).fillna(0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM