pandas如何从ohlc dataframe计算上个月的低值

xsuvu9jc  于 2023-04-28  发布在  其他
关注(0)|答案(1)|浏览(81)

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)
dxxyhpgq

dxxyhpgq1#

你可以用重新采样的最小结果Mapdf的移位索引。
您的设置:

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)

解决方案:

month_low = df["price"].resample('M').min()
df['prev_month_low'] = df.index.shift(-1, "M").map(month_low)

df

price  prev_month_low
date
2022-03-01     10             NaN
2022-03-02      8             NaN
2022-04-01      5             8.0
2022-04-02      7             8.0

相关问题