簡體   English   中英

Python:使用來自另一個 CSV 的條件過濾 CSV

[英]Python: Filtering CSV with conditions from another CSV

我正在嘗試使用 Pandas 編寫 Python 代碼以過濾掉 CSV 文件,具體取決於從另一個 CSV 文件設置的條件。

我要過濾的 CSV 看起來像這樣:

date              product
01/05/2020        Test Product 1
02/05/2020        Test Product 1
03/05/2020        Test Product 1
04/05/2020        Test Product 1
05/05/2020        Test Product 1
06/05/2020        Test Product 1
07/05/2020        Test Product 1
01/05/2020        Test Product 2
02/05/2020        Test Product 2
03/05/2020        Test Product 2
04/05/2020        Test Product 2
05/05/2020        Test Product 2
06/05/2020        Test Product 2
07/05/2020        Test Product 2

CSV 的條件如下:

product               start_date
Test Product 1        01/05/2020
Test Product 2        04/05/2020

我要做的是過濾第一個 CSV 以便任何在 01/05 之后具有 start_date 的測試產品都將刪除相關行。 例如,測試產品 2 的 start_date 為 04/05/2020,這意味着在第一個 CSV 中,我試圖刪除該產品的 01/05、02/05 和 03/05 的行。

這將是所需的 output:

    date              product
01/05/2020        Test Product 1
02/05/2020        Test Product 1
03/05/2020        Test Product 1
04/05/2020        Test Product 1
05/05/2020        Test Product 1
06/05/2020        Test Product 1
07/05/2020        Test Product 1
04/05/2020        Test Product 2
05/05/2020        Test Product 2
06/05/2020        Test Product 2
07/05/2020        Test Product 2

最好的方法是什么? 很長一段時間以來,我一直在嘗試以多種方式使用數據框,但還沒有找到任何正確的腳本......

提前謝謝了!

我們可以使用boolean indexingSeries.map

df_filtered = df1.loc[df1['date'].ge(df1['product']\
                                     .map(df2.set_index('product')['start_date']))]
print(df_filtered)
          date         product
0   01/05/2020  Test Product 1
1   02/05/2020  Test Product 1
2   03/05/2020  Test Product 1
3   04/05/2020  Test Product 1
4   05/05/2020  Test Product 1
5   06/05/2020  Test Product 1
6   07/05/2020  Test Product 1
10  04/05/2020  Test Product 2
11  05/05/2020  Test Product 2
12  06/05/2020  Test Product 2
13  07/05/2020  Test Product 2

為了讀取您的 csv 文件,我們使用pd.read_csv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM