我有两列数据框.日期和十进制数.
我想在数据框中创建一个新列,仅在时间超过9:30时显示十进制数列的cummin
最佳答案 使用面具来掩盖,然后使用cummin.
# df.index = pd.to_datetime(df.index, errors='coerce')
df['cummin'] = df.number.mask(df.index.strftime('%H:%M') < '09:30').cummin()
您还可以查询索引的小时和分钟属性以获取小时数:
df['cummin'] = df.loc[
(df.index.hour >= 9) & (df.index.minute > 30), 'number'].cummin()
MCVE:
df = pd.DataFrame([1.4, 4.5, 2.3],
index=['9:00', '9:31', '9:45'],
columns=['number'])
df.index = pd.to_datetime(df.index)
df
number
2018-12-21 09:00:00 1.4
2018-12-21 09:31:00 4.5
2018-12-21 09:45:00 2.3
df.assign(number=(
df.number.mask(df.index.strftime('%H:%M') < '09:30').cummin()))
number cummin
2018-12-21 09:00:00 NaN NaN
2018-12-21 09:31:00 4.5 4.5
2018-12-21 09:45:00 2.3 2.3
df.assign(number=df.loc[
(df.index.hour >= 9) & (df.index.minute > 30), 'number'].cummin())
number cummin
2018-12-21 09:00:00 NaN NaN
2018-12-21 09:31:00 4.5 4.5
2018-12-21 09:45:00 2.3 2.3