添加多个数据帧并删除不匹配的索引

2024-04-28 05:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

pandasDataFrame.add方法有如下注释:“不匹配的索引将联合在一起”,但我正在寻找删除不匹配索引的最有效方法。你知道吗

我有多个数据帧,每个数据帧都有一个DateTime索引,但是我只想把在我要添加到一起的所有数据帧的任何列中有观察值的日期上的值加在一起。最有效的方法是什么(即删除不匹配的索引而不是合并它们)?你知道吗

iso_country_code  AFG AGO ALB       ARE
period_end
2013-03-31        NaN NaN NaN  7.512557
2013-06-30        NaN NaN NaN  7.455903
2013-09-30        NaN NaN NaN  7.232294
2013-12-31        NaN NaN NaN  7.044918
2014-03-31        NaN NaN NaN  7.049269
2014-06-30        NaN NaN NaN  8.621573
2014-09-30        NaN NaN NaN       NaN
2014-12-31        NaN NaN NaN       NaN

iso_country_code       AFG       AGO        ALB        ARE
period_end
2013-03-31        0.083310  4.164154  20.002821  17.463841
2013-06-30        0.092613  5.129979  20.389471  17.774866
2013-09-30        0.048484  5.116080  20.641199  17.535600
2013-12-31        0.067519  3.632584  21.494163  18.122075
2014-03-31        0.242996  3.686424  18.178002  19.399709
2014-06-30             NaN       NaN        NaN        NaN
2014-09-30             NaN       NaN        NaN        NaN
2014-12-31             NaN       NaN        NaN        NaN

*程序完成*


Tags: 数据方法adddatetimecodeisonanago
1条回答
网友
1楼 · 发布于 2024-04-28 05:00:37

应该简单到:

(df1 + df2).dropna(axis=0, how='all').dropna(axis=1, how='all')

如果不起作用,请尝试:

df1.add(df2).dropna(axis=0, how='all').dropna(axis=1, how='all')

我现在不能测试写,但这两个(或至少一个)都会给您留下:

iso_country_code  ARE
period_end
2013-03-31        25.xxx
2013-06-30        xx.xxx
2013-09-30        xx.xxx
2013-12-31        xx.xxx
2014-03-31        xx.xxx
2014-06-30        xx.xxx

相关问题 更多 >