英文:
Get a result based on previous row in Python
问题
以下是您提供的内容的中文翻译部分:
我正在处理以下问题。我正在分析第一次尝试后发生了什么。 Rank
> 1
我成功地准备了数据,通过基于 Date
的排名 (Rank
)。在下面的示例中,我尝试获取所有 Col1
中的带有 ID1
的行,因为 Col2
中的 ID1
具有相同的值 (TEST1
)。
我对 ID2
或 ID3
不感兴趣,因为它们不再具有另一个 Test1
。
df(print)
Col1 Col2 Date Rank
ID1 TEST1 01/07 1
ID2 TEST1 01/07 1
ID3 TEST1 01/07 1
ID1 TEST1 02/07 2
ID2 TEST2 02/07 2
ID3 TEST3 04/07 2
期望的输出
df(print)
Col1 Col2 Date Rank
ID1 TEST1 01/07 1
ID1 TEST1 02/07 2
我尝试了 if else
和 np.where
语句,但它们没有起作用。
编辑:我希望我的查询能够自动检测到 TEST1 具有排名 1,并在排名 2 也具有 TEST1 时提供数据。
希望这样能够理解。
英文:
I am struggling with the following. I am analysing of what happened after first attempt. Rank
> 1
I managed to prepare the data, by ranking (Rank
) based on Date
. In the example below, I`m trying to get all Rows with ID1
from Col1
, as ID1
has the same value (TEST1
) in Col2
.
I am not interested in ID2
or ID3
as they don't have another Test1
anymore.
df(print)
Col1 Col2 Date Rank
ID1 TEST1 01/07 1
ID2 TEST1 01/07 1
ID3 TEST1 01/07 1
ID1 TEST1 02/07 2
ID2 TEST2 02/07 2
ID3 TEST3 04/07 2
Desired output
df(print)
Col1 Col2 Date Rank
ID1 TEST1 01/07 1
ID1 TEST1 02/07 2
I have tried the if else
and np.where
statement, but those did not work.
Edit: I want my query to automatically detect that TEST1 has rank 1 and provide me with data, if rank 2 has also TEST1.
Hope this makes sense.
答案1
得分: 1
我不知道你需要多通用,但要获取该输出,您可以使用
```python
df[(df['Col1']=='ID1') & (df['Rank']>1)]
通常情况下,df[conditions]
,其中条件由&
连接,并由(...)
分组,类似于SQL的WHERE
子句。
<details>
<summary>英文:</summary>
I don't know how general you need this, but to get that output you can use
```python
df[(df['Col1']=='ID1') & (df['Rank']>1)]
In general df[conditions]
where the conditions are joined by &
, and are grouped by (...)
, is similar to a SQL WHERE
clause.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论