一个样本系列的resample()DataFrame,同时在DataFrame中复制所有其他系列的值 [英] resample() DataFrame for one Series, while copying values of all other Series in DataFrame

查看:308
本文介绍了一个样本系列的resample()DataFrame,同时在DataFrame中复制所有其他系列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对DataFrame中的一个系列进行重新采样,其中DataFrame中的所有其他系列对于每个索引都具有相同的数据.我可以对一个系列进行重新采样,但是如何复制数据呢?

I want to resample on one Series in a DataFrame, where all other Series in the DataFrame have identical data for each index. I can resample the one Series in question, but how do I copy the data over?

如果我以df开头:

                    value    data_1 data_2  data_3  data_4
effective_date                                            
2018-7-31        4.010784  17901701   3mra  Actual    0.01
2018-8-31        2.044298  17901701   3mra  Actual    0.01
2018-10-31      11.493831  17901701   3mra  Actual    0.01
2018-11-30      13.929844  17901701   3mra  Actual    0.01
2018-12-31      21.500490  17901701   3mra  Actual    0.01

并希望在9月日期中添加值0,所有其他数据均保持不变:

And want to add in the September date with a value of 0 and all other data remaining the same:

                    value    data_1 data_2  data_3  data_4
effective_date                                            
2018-7-31        4.010784  17901701   3mra  Actual    0.01
2018-8-31        2.044298  17901701   3mra  Actual    0.01
2018-9-30        0.000000  17901701   3mra  Actual    0.01
2018-10-31      11.493831  17901701   3mra  Actual    0.01
2018-11-30      13.929844  17901701   3mra  Actual    0.01
2018-12-31      21.500490  17901701   3mra  Actual    0.01

到目前为止的代码

我可以使用以下代码对value进行重新采样:

Code so far

I can resample value with the following code:

df.value.resample('M').first().fillna(0)

获得:

effective_date
2018-07-31     4.010784
2018-08-31     2.044298
2018-09-30     0.000000
2018-10-31    11.493831
2018-11-30    13.929844
2018-12-31    21.500490

将其他值复制到df的最有效方法是什么?

What's the most efficient way to copy the other values into df?

推荐答案

您可以使用resample重新对整个DataFrame进行采样,然后使用0填充所有值"列的NA,并使用其他所有列填充ffill:

You can resample the whole DataFrame with resample, then fill NA's for 'value' column with 0's and ffill all other columns:

df.resample('M').first().fillna({'value': 0}).ffill()

输出:

                    value      data_1 data_2  data_3  data_4
effective_date                                              
2018-07-31       4.010784  17901701.0   3mra  Actual    0.01
2018-08-31       2.044298  17901701.0   3mra  Actual    0.01
2018-09-30       0.000000  17901701.0   3mra  Actual    0.01
2018-10-31      11.493831  17901701.0   3mra  Actual    0.01
2018-11-30      13.929844  17901701.0   3mra  Actual    0.01
2018-12-31      21.500490  17901701.0   3mra  Actual    0.01

这篇关于一个样本系列的resample()DataFrame,同时在DataFrame中复制所有其他系列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆