我正在使用非常方便的 pandas dataframe last(..) 函数。在我的用例中,我正在执行以下操作以获取属于上个月数据的所有样本(我正在处理每日数据,使用 2D 频率不污染问题):
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': np.random.rand(10)},
index=pd.date_range('2020-06-23', periods=10, freq='2D'))
print(df)
A
2020-06-23 0.893443
2020-06-25 0.256981
2020-06-27 0.544561
2020-06-29 0.712149
2020-07-01 0.500871
2020-07-03 0.948928
2020-07-05 0.816448
2020-07-07 0.939283
2020-07-09 0.760055
2020-07-11 0.394204
print(df.last('1M'))
A
2020-07-01 0.500871
2020-07-03 0.948928
2020-07-05 0.816448
2020-07-07 0.939283
2020-07-09 0.760055
2020-07-11 0.394204
我基本上想要最后的结果加上上个月的最后一个样本:
A
2020-06-29 0.712149
2020-07-01 0.500871
2020-07-03 0.948928
2020-07-05 0.816448
2020-07-07 0.939283
2020-07-09 0.760055
2020-07-11 0.394204
我需要上个月加上之前的单个样本(由于计算上个月第一天的返回,还需要第一个日期的 t-1)。我可以想出一种更复杂的方法来做到这一点,但我想知道是否有一种惯用且优雅的方法来做到这一点,而不是放弃很好的 last
用例。
最佳答案
我认为没有任何内置的 pandas 方法或参数可以像 pd.DataFrame.last
那样方便,但是,我认为一种实用的方法是使用数据帧索引和 tail
:
df = pd.DataFrame({'A': np.random.rand(10)},
index=pd.date_range('2020-06-23', periods=10, freq='2D'))
last_month = df.last('1M')
last_month = pd.concat([df[~df.index.isin(last_month.index)].tail(1),
last_month])
last_month
输出:
A
2020-06-29 0.782871
2020-07-01 0.695212
2020-07-03 0.704208
2020-07-05 0.058842
2020-07-07 0.632520
2020-07-09 0.746908
2020-07-11 0.867645
关于python - 有没有一种简单的方法可以在最后一个数据框中包含第一个值之前的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63055205/