Python 尝试在具有多行条件的数据库中进行迭代
事先道歉。我对python非常陌生。 我已经创建了一个带有日期时间戳的索引。我希望根据特定列和下一行中的同一列的条件遍历所有行。基于下面的示例,我想对照绝对值检查“Streak”列,例如3,然后检查下一行,查看Streak列是否变为负值 由于时间戳索引,我正在努力查看下一行。我尝试过Python 尝试在具有多行条件的数据库中进行迭代,python,pandas,python-2.7,Python,Pandas,Python 2.7,事先道歉。我对python非常陌生。 我已经创建了一个带有日期时间戳的索引。我希望根据特定列和下一行中的同一列的条件遍历所有行。基于下面的示例,我想对照绝对值检查“Streak”列,例如3,然后检查下一行,查看Streak列是否变为负值 由于时间戳索引,我正在努力查看下一行。我尝试过.shift()和多次尝试loc和iloc以及Timedelta。后者的问题在于,每行上的时间戳之间没有一致的差异 我的df看起来像 Security Difference
.shift()
和多次尝试loc
和iloc
以及Timedelta
。后者的问题在于,每行上的时间戳之间没有一致的差异
我的df看起来像
Security Difference Buy/Sell Streak Price
Date
2019-02-25 2330 500.0 1 1 238.0
2019-02-26 2330 400.0 1 2 239.0
2019-02-27 2330 200.0 1 3 239.5
2019-03-05 2330 -600.0 -1 -1 233.0
2019-03-06 2330 190.0 1 1 234.0
我尝试过但失败的代码是
strikelength=3
对于索引,mergeddf.iterrows()中的行:
currentrow=mergeddf.index.get_loc(索引)
如果(mergeddf.iloc[currentrow,'Streak']>=streaklength&(mergeddf.iloc[currentrow+1,'Streak'])==-1:
做点什么
编辑-在轮流输出时,我希望获得原始行的“Price”列和固定行数的列的Price Price,然后返回该比率
因此,对于固定行移动n=2的原始示例,我想返回一个变量ouput1(239.5)和ouput2(234),并返回output1/output2的比率,如果我正确理解了这个问题,您需要的是
(df.Streak>=3)和(df.Streak.shift(-1)
稍微更改您自己示例中的第一行,以确保满足这两个条件,这将提供以下内容:
In [15]: df
Out[15]:
Security Difference Buy/Sell Streak Price
Date
2019-02-25 2330 500.0 1 3 238.0
2019-02-26 2330 400.0 1 2 239.0
2019-02-27 2330 200.0 1 3 239.5
2019-03-05 2330 -600.0 -1 -1 233.0
2019-03-06 2330 190.0 1 1 234.0
In [16]: (df.Streak >= 3) & (df.Streak.shift(-1) < 0)
Out[16]:
Date
2019-02-25 False
2019-02-26 False
2019-02-27 True
2019-03-05 False
2019-03-06 False
Name: Streak, dtype: bool
In [139]: df
Out[139]:
Security Difference Buy/Sell Streak Price Output1 Output2
Date
2019-02-25 2330 500.0 1 3 238.0 NaN NaN
2019-02-26 2330 400.0 1 2 239.0 NaN NaN
2019-02-27 2330 200.0 1 3 239.5 239.5 1.023504
2019-03-05 2330 -600.0 -1 -1 233.0 NaN NaN
2019-03-06 2330 190.0 1 1 234.0 NaN NaN
或者提供预期的输出。你的意思是df.loc[df.Streak.eq(3.shift().fillna(False),'Streak'].lt(0)
?返回true。谢谢。当我在代码中尝试此解决方案时,我得到的序列真值是不明确的。您是否使用了和而不是&
,或者删除了括号?否-如上所示。我在尝试从@anky_91;响应时得到了相同的错误。我可以使用在.iterrows
循环中,但一旦进入循环,我就会得到不明确的序列error@NS7274:这里的想法是完全避免循环,同时在所有行上测试条件。
In [139]: df
Out[139]:
Security Difference Buy/Sell Streak Price Output1 Output2
Date
2019-02-25 2330 500.0 1 3 238.0 NaN NaN
2019-02-26 2330 400.0 1 2 239.0 NaN NaN
2019-02-27 2330 200.0 1 3 239.5 239.5 1.023504
2019-03-05 2330 -600.0 -1 -1 233.0 NaN NaN
2019-03-06 2330 190.0 1 1 234.0 NaN NaN