我有以下資料
jsonDict = {'Fruit': ['apple', 'orange', 'apple', 'banana', 'orange', 'apple','banana'], 'price': [1, 2, 1, 3, 2, 1, 3]}
Fruit price
0 apple 1
1 orange 2
2 apple 1
3 banana 3
4 orange 2
5 apple 1
6 banana 3
我想要做的是檢查是否Fruit == banana,如果是,我希望代碼n從“香蕉”行的索引位置掃描前一行和下一行,例如 where Fruit == apple. 預期輸出的示例如下所示n=2。
Fruit price
2 apple 1
5 apple 1
我試過做
position = df[df['Fruit'] == 'banana'].index
resultdf= df.loc[((df.index).isin(position)) & (((df['Fruit'].index 2).isin(['apple']))|((df['Fruit'].index-2).isin(['apple'])))]
# Output is an empty dataframe
Empty DataFrame
Columns: [Fruit, price]
Index: []
將優先考慮矢量化方法。
uj5u.com熱心網友回復:
IIUC,您可以使用 2 個掩碼和布爾索引:
# df = pd.DataFrame(jsonDict)
n = 2
m1 = df['Fruit'].eq('banana')
# is the row ±n of a banana?
m2 = m1.rolling(2*n 1, min_periods=1, center=True).max().eq(1)
# is the row an apple?
m3 = df['Fruit'].eq('apple')
out = df[m2&m3]
輸出:
Fruit price
2 apple 1
5 apple 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/518247.html
上一篇:在R中的特定列數中轉置資料幀
下一篇:帶有中值標簽的箱線圖和下面的n表
