根据时间条件将数据帧的一部分与特定值相乘

时间:2019-06-04 17:43:21

标签: python pandas dataframe

我想将指定时间内的值与一个值相乘

尝试了以下内容,这些内容在我一次执行后仍然有效,但是我认为我无法多次重新分配。只有1条线有效,但多于一条给出NaN。在仍然将乘法应用于特定时间范围的同时如何避免这种情况?

onpeak_increase  = 1.2
offpeak_decrease = 0.8
df2 = df2.between_time('07:00:00', '11:00:00', include_start=True, include_end=False) * onpeak_increase
df2 = df2.between_time('16:00:00', '20:00:00', include_start=True, include_end=False) * onpeak_increase
df2 = df2.between_time('20:00:00', '07:00:00', include_start=True, include_end=True) * offpeak_decrease
df2 = df2.between_time('11:00:00', '16:00:00', include_start=True, include_end=False) * offpeak_decrease

1 个答案:

答案 0 :(得分:1)

问题是df.between_time提取了相应的行,因此您在每一步都将数据框设置为这些行。
因此,如果我了解您想要什么,我会做这样的事情:

idx = df2.between_time('07:00:00', '11:00:00', include_start=True, include_end=False).index
df2.loc[idx] = df2.loc[idx].values * onpeak_increase

idx = df2.between_time('16:00:00', '20:00:00', include_start=True, include_end=False).index
df2.loc[idx] = df2.loc[idx].values * onpeak_increase

idx = df2.between_time('20:00:00', '07:00:00', include_start=True, include_end=True).index
df2.loc[idx] = df2.loc[idx].values * offpeak_decrease

idx = df2.between_time('11:00:00', '16:00:00', include_start=True, include_end=False).index
df2.loc[idx] = df2.loc[idx].values * offpeak_decrease

我假设您想将与该范围相对应的行的值相乘