python pandas - 在 cummax() 处检索索引时间戳值

标签 python pandas

我正在检索以下数据帧的 cummax() 值,

                     exit_price  trend  netgain     high      low   MFE_pr
exit_time                                                                 
2000-02-01 01:00:00     1400.25     -1     1.00  1401.50  1400.25  1400.25
2000-02-01 01:30:00     1400.75     -1     0.50  1401.00  1399.50  1399.50
2000-02-01 02:00:00     1400.00     -1     1.25  1401.00  1399.75  1399.50
2000-02-01 02:30:00     1399.25     -1     2.00  1399.75  1399.25  1399.25
2000-02-01 03:00:00     1399.50     -1     1.75  1400.00  1399.50  1399.25
2000-02-01 03:30:00     1398.25     -1     3.00  1399.25  1398.25  1398.25
2000-02-01 04:00:00     1398.75     -1     2.50  1399.00  1398.25  1398.25
2000-02-01 04:30:00     1400.00     -1     1.25  1400.25  1399.00  1398.25
2000-02-01 05:00:00     1400.25     -1     1.00  1400.50  1399.25  1398.25
2000-02-01 05:30:00     1400.50     -1     0.75  1400.75  1399.50  1398.25

使用以下公式

trade ['MFE_pr'] = np.nan
trade ['MFE_pr'] = trade ['MFE_pr'].where(trade ['trend']<0, trade.high.cummax())
trade ['MFE_pr'] = trade ['MFE_pr'].where(trade ['trend']>0, trade.low.cummin())

有没有办法检索每行的 cummax() 所在行的时间戳?类似于 .idxmax() 但对于 cummax() ?

最佳答案

这可能就是您正在寻找的内容。

import pandas as pd
import datetime
df = pd.DataFrame({'a': [1, 2, 1, 3, 2, 5, 4, 3, 5]}, 
                  index=pd.DatetimeIndex(start=
                                         datetime.datetime.fromtimestamp(0),
                                        periods=9, freq='D'))
df['cummax'] = df.a.cummax()
df['timestamp'] = df.index
df = df.merge(df.groupby('cummax')[['timestamp']].first().reset_index(), on='cummax')
df.rename(columns={'timestamp_y': 'max_timestamp'}, inplace=True)
df.index=df.timestamp_x.values
del df['timestamp_x']
print(df)


                     a  cummax       max_timestamp
1970-01-01 03:00:00  1       1 1970-01-01 03:00:00
1970-01-02 03:00:00  2       2 1970-01-02 03:00:00
1970-01-03 03:00:00  1       2 1970-01-02 03:00:00
1970-01-04 03:00:00  3       3 1970-01-04 03:00:00
1970-01-05 03:00:00  2       3 1970-01-04 03:00:00
1970-01-06 03:00:00  5       5 1970-01-06 03:00:00
1970-01-07 03:00:00  4       5 1970-01-06 03:00:00
1970-01-08 03:00:00  3       5 1970-01-06 03:00:00
1970-01-09 03:00:00  5       5 1970-01-06 03:00:00

关于python pandas - 在 cummax() 处检索索引时间戳值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819246/

相关文章:

python - 在 apscheduler 中捕获日志

python - Django 最佳实践 - 何时使用 View 、何时使用标签

python - MySQL/Python -> 语句中占位符的语法错误?

python - Pandas 数据框 : selecting max by column for subset

python - Pandas 根据独特值进行分组和聚合

python - 如何从数据框中找到句子中单词和字符的最大数量?

c++ - 将指针数组转换到其他对象?

具有随机属性的对象的Python列表

python - 将风向字典映射到新列

python - Pandas :SettingWithCopyWarning: