Python 基于上一行生成列中的值

Python 基于上一行生成列中的值,python,pandas,jupyter,Python,Pandas,Jupyter,让我们假设我在一个固定的时间间隔内进行温度测量,并在一个数据帧中记录这些值 day temperature [F] 0 89 1 91 2 93 3 88 4 90 现在我想创建另一个列,当且仅当前面的两个值高于某个级别时,将其设置为1。在我的场景中,如果两个连续的值大于90,那么我希望创建一个列值1,从而产生 day temperature

让我们假设我在一个固定的时间间隔内进行温度测量,并在一个数据帧中记录这些值

day   temperature [F]
0       89          
1       91         
2       93         
3       88            
4       90
现在我想创建另一个列,当且仅当前面的两个值高于某个级别时,将其设置为1。在我的场景中,如果两个连续的值大于90,那么我希望创建一个列值1,从而产生

day   temperature        Above limit?
0       89               0
1       91               0
2       93               1
3       88               0
4       91               0
5       91               1
6       93               1
尽管有一些SO和Google挖掘,但不清楚我是否可以在for循环中使用iloc[x]、loc[x]或其他东西?

试试这个:

df = pd.DataFrame({'temperature': [89, 91, 93, 88, 90, 91, 91, 93]})

limit = 90
df['Above'] = ((df['temperature']>limit) & (df['temperature'].shift(1)>limit)).astype(int)
df
将来,请包括测试代码(在本例中为df构造线)

这里iloc[i,2]指第i行索引和第2列索引(限制列)。希望这对您在pandas中查找函数有所帮助


输入io
作为pd进口熊猫
data=”“”
预期日间气温
0       89               0
1       91               0
2       93               1
3       88               0
4       91               0
5       91               1
6       93               1
"""
数据=io.StringIO(数据)
df=pd.read_csv(数据,sep='\s+')
df['Result']=((df['temperature'].shift(1)>90)和(df['temperature']>90)).astype(int)
#验证
(df['Result']==df['Expected'])。全部()
解决方案使用:

尝试使用并应用(),如下所示:

df["limit"]=df['temperature'].rolling(2).apply(lambda x: int(x[0]>90)&int(x[-1]> 90))

啊,比我快了几分钟。对于数据构建,我经常使用
io
库来复制和粘贴样本数据并将其读入。我很少看到有人发布示例代码来创建他们的数据集:(我同意,在没有发布示例的情况下,这是一个很好的解决方法。这只是对良好实践的一个评论,因为它使回答变得更容易。感谢你在发布df构造行时的提醒。我会给自己十个鞭子
>> threshold = 90
>> df['Above limit?'] = 0
>> df.loc[((df['temperature [F]'] > threshold) & (df['temperature [F]'].shift(1) > threshold)), 'Above limit?'] = 1
>> df
    day temperature [F] Above limit?
0   0   89              0
1   1   91              0
2   2   93              1
3   3   88              0
4   4   90              0
df["limit"]=df['temperature'].rolling(2).apply(lambda x: int(x[0]>90)&int(x[-1]> 90))