Dataframe:添加 'inplace' 列,其中包含出现在 datetime.index 中的日期的 cumcount()

Dataframe: Add 'inplace' a column with the cumcount() of the dates appeared in the datetime.index

我想添加一列(使用 header 'acc_dates'),它会在具有日期时间索引的数据框中增加日期计数。这是一个例子:

import pandas as pd
import datetime as dt

datarange=pd.date_range('01-05-2018 00:00:00', periods=50, freq="4H")
range_series_1=pd.Series(np.random.randint(-5,3,size=50).astype(float), index=datarange)
df=pd.DataFrame({'value1':range_series_1})

df.head(5)
Out[287]: 
                     value1
datetime                   
2018-01-05 00:00:00     1.0
2018-01-05 04:00:00    -2.0
2018-01-05 08:00:00    -2.0
2018-01-05 12:00:00    -3.0
2018-01-05 16:00:00     1.0

如果我应用 cumcount(),'value1' 列就会消失。这是我输入的和得到的:

df.groupby(df.index.date).cumcount().to_frame('acc_dates').head(15)
Out[288]: 
                     acc_dates
datetime                      
2018-01-05 00:00:00          0
2018-01-05 04:00:00          1
2018-01-05 08:00:00          2
2018-01-05 12:00:00          3
2018-01-05 16:00:00          4
2018-01-05 20:00:00          5
2018-01-06 00:00:00          0
2018-01-06 04:00:00          1
2018-01-06 08:00:00          2
2018-01-06 12:00:00          3
2018-01-06 16:00:00          4
2018-01-06 20:00:00          5
2018-01-07 00:00:00          0
2018-01-07 04:00:00          1
2018-01-07 08:00:00          2

我可以合并 'datetime' 上的两个数据帧以获得所需的输出,但我宁愿不应用 pd.merge() 方法。这是我期望的输出:

Out[296]:
                     value1  acc_dates
datetime                              
2018-01-05 00:00:00     1.0          0
2018-01-05 04:00:00    -2.0          1
2018-01-05 08:00:00    -2.0          2
2018-01-05 12:00:00    -3.0          3
2018-01-05 16:00:00     1.0          4
2018-01-05 20:00:00     0.0          5
2018-01-06 00:00:00     2.0          0
2018-01-06 04:00:00    -3.0          1
2018-01-06 08:00:00    -5.0          2
2018-01-06 12:00:00    -5.0          3
2018-01-06 16:00:00     1.0          4
2018-01-06 20:00:00    -2.0          5
2018-01-07 00:00:00     2.0          0
2018-01-07 04:00:00     1.0          1
2018-01-07 08:00:00    -1.0          2
2018-01-07 12:00:00    -2.0          3

理想情况下,我正在寻找一种方法来以某种方式在初始 df inplace.

中创建和添加列

这可行吗?我欢迎你的建议。

我认为 mergeconcat 不是必需的,只需将输出分配给新列:

df['acc_dates'] = df.groupby(df.index.date).cumcount()