【问题标题】:Filter rows in csv based on custom condition根据自定义条件过滤 csv 中的行
【发布时间】:2020-08-03 23:28:54
【问题描述】:

假设我有一个如下所示的 csv

+-----+-----------+---------+
| ID  | state     | city    |
+-----+-----------+---------+
| 101 | READY     |         |
| 101 | DELIVERED | NEWYORK |
| 101 | DELIVERED | LONDON  |   
| 102 | READY     |         |
| 102 | DELIVERED | LONDON  |
| 103 | READY     |         |
| 103 | DELIVERED | NEWYORK |
| 104 | READY     |         |
| 104 | DELIVERED | TOKYO   |
| 104 | DELIVERED | PARIS   |
| 105 | DELIVERED | NEWYORK |
+-----+-----------+---------+

现在我想要状态为READY 的ID,其中DELIVEREDNEWYORK

  • 相同的 ID 将多次出现在不同的州和城市。
  • READYcity 始终为空
  • DELIVEREDcity 总是会有一些值。

所以首先我想检查列city 的值是否已交付state。如果是 NEWYORK,则取该 ID 的 READY 行。如果没有READY 行,那么我们可以忽略(本例中为ID 105)

预期输出

+-----+-----------+---------+
| ID  | state     | city    |
+-----+-----------+---------+
| 101 | READY     |         |
| 103 | READY     |         |
+-----+-----------+---------+

我尝试在 pandas 中使用自加入。但我不知道如何进一步进行,因为我是 python 新手。目前我正在 SQL 中执行此操作。

import pandas as pd
mydata = pd.read_csv('C:/Mypython/Newyork',encoding = "ISO-8859-1")
NY = pd.merge(mydata,mydata,left_on='ID',right_on='ID',how='inner')

【问题讨论】:

    标签: python pandas filter


    【解决方案1】:

    让我们尝试使用groupby().transform() 来识别具有NEWYORK 的那些,然后进行布尔索引:

    has_NY = df['city'].eq('NEWYORK').groupby(df['ID']).transform('any')
    
    mask = df['state'].eq('READY') & has_NY
    
    df[mask]
    

    输出:

        ID  state  city
    0  101  READY  None
    5  103  READY  None
    

    【讨论】:

      【解决方案2】:

      使用 NEWYORK 条件获取 ID 列表,然后使用该列表进行过滤。

      new_york_ids = df.loc[df['city']=='NEWYORK', 'ID']
      df[(df['state']=='READY') & (df['ID'].isin(new_york_ids))]
      
          ID  state  city
      0  101  READY  None
      5  103  READY  None
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2012-12-08
        • 2018-11-25
        • 1970-01-01
        • 1970-01-01
        • 2018-09-10
        相关资源
        最近更新 更多