[英]How to join two tables with dates conditions with SQL and Python?
[英]How to join two tables with special conditions
我有兩個具有相同功能的DataFrame:
customer_id Class value
1 A 13
2 A 14
3 B 15
customer id Class value
1 A 16
2 B 17
3 B 18
4 A 20
現在我想要1個DataFrame,其中包括將類別從A更改為B的客戶
customer_id Class value
2 B 17
我怎樣才能做到這一點?
假設您的DataFrame是df1
和df2
,則可以在客戶上合並它們:
before_after = pd.merge(df1, df2, on='customer', how='left', suffixes=('_before', '_after'))
然后檢查哪個從'A'
更改為'B'
:
before_after[(before_after.id_before == 'A') & (before_after.id_after == 'B')]
您可以在過濾第二個數據幀之前執行映射:
df2['Class_original'] = df2['customer_id'].map(df1.set_index('customer_id')['Class'])
res = df2[(df2['Class_original'] == 'A') & (df2['Class'] == 'B')]
print(res)
customer_id Class value Class_original
1 2 B 17 A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.