pandas如何从ohlc dataframe计算上个月的低值并将其添加回同一dataframe以下代码不起作用
import pandas as pd
# create example DataFrame
df = pd.DataFrame({'date': ['2022-03-01', '2022-03-02', '2022-04-01', '2022-04-02'],
'price': [10, 8, 5, 7]})
# convert date column to datetime object
df['date'] = pd.to_datetime(df['date'])
# set date column as index
df.set_index('date', inplace=True)
# resample to monthly frequency and calculate minimum value
previous_month_low = df.resample('M')['price'].min()
# shift index by one month
previous_month_low.index = previous_month_low.index.shift(1, freq='M')
# define function to return previous month low for each date
def get_prev_month_low(date):
prev_month = date - pd.offsets.MonthBegin(1)
prev_month_low = previous_month_low.loc[prev_month.strftime('%Y-%m-%d')]
return prev_month_low
# create a new column in the original dataframe
df['prev_month_low'] = df.index.to_series().apply(get_prev_month_low)
print(df)
1条答案
按热度按时间dxxyhpgq1#
你可以用重新采样的最小结果Mapdf的移位索引。
您的设置:
解决方案:
df
: