基于前一行在Python中获取结果

huangapple go评论77阅读模式
英文:

Get a result based on previous row in Python

问题

以下是您提供的内容的中文翻译部分:

我正在处理以下问题。我正在分析第一次尝试后发生了什么。 Rank > 1

我成功地准备了数据,通过基于 Date 的排名 (Rank)。在下面的示例中,我尝试获取所有 Col1 中的带有 ID1 的行,因为 Col2 中的 ID1 具有相同的值 (TEST1)。

我对 ID2ID3 不感兴趣,因为它们不再具有另一个 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 elsenp.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&#39;t know how general you need this, but to get that output you can use 

```python
df[(df[&#39;Col1&#39;]==&#39;ID1&#39;) &amp; (df[&#39;Rank&#39;]&gt;1)]

In general df[conditions] where the conditions are joined by &amp;, and are grouped by (...), is similar to a SQL WHERE clause.

huangapple
  • 本文由 发表于 2023年7月5日 00:02:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定