【发布时间】:2017-09-10 09:33:27
【问题描述】:
我有一个带有时间戳日期时间索引和对应于每个日期的值的 pandas DataFrame。例如,df = pd.DataFrame(['0.11', '0.07', '0.04', '-0.11', '-0.04', '0.08', '0.1'], index=['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04', '2017-01-05', '2017-01-06', '2017-01-07'], columns=['values'])。
我想根据上述数据框的当前值和历史值创建一个额外的列(我们称之为'new_value')。
逻辑应该是:
- 如果值大于或等于 0.1,则应设置“new_value” 到 -1,
- 一旦 'new_value' 设置为 -1,它应该保持 -1 直到一个值 小于或等于 0.05 被注册,
- 如果值小于或等于-0.1,则应设置'new_value' +1,
- 一旦 'new_value' 设置为 +1,它应该保持 +1 直到一个值 大于或等于 -0.05 被注册,
- 否则 'new_value' 等于 0
我尝试了多种解决方案,但似乎无法解决这个问题。例如,
new_frame = pd.DataFrame(np.zeros(len(df.index),index=df.index,columns=['new_value'])
for date in df.index:
if df['value'][date.strftime('%Y-%m-%d')] > 0.1:
new_frame.set_value(date.strftime("%Y-%m-%d"),'new_value',-1)
但我收到错误:'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().'
如果我将第三行更改为:
if df['value'][date.strftime('%Y-%m-%d').item() > 0.1:
我收到错误:'ValueError: can only convert an array of size 1 to a Python scalar'
【问题讨论】:
标签: pandas numpy time-series logical-operators