我有兩個資料框,我需要根據條件在兩列之間進行比較并列印輸出。例如:
df1:
| ID | Date | value |
| 248 | 2021-10-30| 4.5 |
| 249 | 2021-09-21| 5.0 |
| 100 | 2021-02-01| 3,2 |
df2:
| ID | Date | value |
| 245 | 2021-12-14| 4.5 |
| 246 | 2021-09-21| 5.0 |
| 247 | 2021-10-30| 3,2 |
| 248 | 2021-10-30| 3,1 |
| 249 | 2021-10-30| 2,2 |
| 250 | 2021-10-30| 6,3 |
| 251 | 2021-10-30| 9,1 |
| 252 | 2021-10-30| 2,0 |
我想撰寫一個比較兩個資料框之間的 ID 列和日期列的代碼,其條件如下所示,
如果“ID 和日期從 df1 到 df2 匹配”: print(df1['compare'] = 'Both matching')
如果“ID 匹配且日期從 df1 到 df2 不匹配”: print(df1['compare'] = 'Date not matching')
如果“ID 與 df1 到 df2 不匹配”:print(df1['compare'] = 'ID not available')
我的結果df1應該如下所示:
df1(預期結果):
| ID | Date | value | compare
| 248 | 2021-10-30| 4.5 | Both matching
| 249 | 2021-09-21| 5.0 | Id matching - Date not matching
| 100 | 2021-02-01| 3,2 | Id not available
如何用 Python 熊貓資料框做到這一點?
uj5u.com熱心網友回復:
我建議你做的是使用iterrows. 這可能不是最好的主意,但仍然可以解決您的問題:
compareColumn = []
for index, row in df1.iterrows():
df2Row = df2[df2["ID"] == row["ID"]]
if df2Row.shape[0] == 0:
compareColumn.append("ID not available")
else:
check = False
for jndex, row2 in df2Row.iterrows():
if row2["Date"] == row["Date"]:
compareColumn.append("Both matching")
check = True
break
if check == False:
compareColumn.append("Date not matching")
df1["compare"] = compareColumn
df1
輸出
| ID | 日期 | 價值 | 比較 | |
|---|---|---|---|---|
| 0 | 248 | 2021-10-30 | 4.5 | 兩者匹配 |
| 1 | 249 | 2021-09-21 | 5 | 日期不匹配 |
| 2 | 100 | 2021-02-01 | 3.2 | 身份證不可用 |
uj5u.com熱心網友回復:
假設“ID”列是索引,那么我們可以這樣做:
def f(x):
if x.name in df2.index:
return 'Both matching' if x['Date']==df2.loc[x.name,'Date'] else 'Date not matching'
return 'ID not available'
df1 = df1.assign(compare=df1.apply(f,1))
print(df1)
Date value compare
ID
248 2021-10-30 4.5 Both matching
249 2021-09-21 5.0 Date not matching
100 2021-02-01 3,2 ID not available
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/442821.html
標籤:Python python-3.x 熊猫 数据框
下一篇:Boto3上傳資料的問題
