我已經使用以下腳本達到了一定程度,即使使用“is.in”這樣的函式,我也無法完全接受它,可能是因為在此之前我從未使用過它。
輸入df1:
ID Alternative ID
0 152503 009372
1 249774 249774
2 062005 196582
3 185704 185704
4 081231 081231
5 081231 062085
6 912568 222416
7 196782 195122
輸入df2:
New_ID
0 498109
1 081231
2 231051
3 062005
4 152503
5 967272
6 875612
這個想法是我想檢查“ID”的值是否與來自df1的“替代ID”上的值匹配。如果他們這樣做,它應該分別在名為“Result_1”和“Result_2”的兩個新列上回傳“Match”和“Correct”。對于不匹配的那些,在df2的“New_ID”列中查找它們是否存在。如果它們在上面提到的那兩列上分別回傳“NEW Match”和“Good”的值。如果它們不存在,則回傳“不匹配”和“錯誤”。
對于此任務的第一部分,這是我使用的代碼:
def compl(df1):
if (df1['ID'] == df1['Alternative ID']):
return 'Match', 'Correct'
elif (df1['ID'] != df1['ID']):
在這里我找不到下一步基本上檢查不匹配的值是否在 df2 等中。
df1[['Result_1', 'Result_2']] = df1.apply(compl, axis = 1, result_type = 'expand')
理想的輸出 ->
ID Alternative ID Result_1 Result_2
0 152503 009372 NEW Match Good
1 249774 249774 Match Correct
2 062005 196582 NEW Match Good
3 185704 185704 Match Correct
4 081231 062085 Match Correct
5 912568 222416 Not Match Error
6 196782 195122 Not Match Error
任何建議/方法將不勝感激
uj5u.com熱心網友回復:
使用np.select與您的條件和所需的值。對于每個條件的真實性,該函式select將映射給定的值。
import numpy as np
conditions = [
df1['ID'] == df1['Alternative ID'],
df1['ID'].isin(df2['New_ID'])
]
values_result1 = ['Match', 'New match']
values_result2 = ['Correct', 'Good']
df1['Result_1'] = np.select(conditions, values_result1, 'No match')
df1['Result_2'] = np.select(conditions, values_result2, 'Error')
輸出
ID Alternative ID Result_1 Result_2
0 152503 9372 New match Good
1 249774 249774 Match Correct
2 62005 196582 New match Good
3 185704 185704 Match Correct
4 81231 81231 Match Correct
5 81231 62085 New match Good
6 912568 222416 No match Error
7 196782 195122 No match Error
注意:您的答案加上一些更多的調整將起作用。但是它會比上面的矢量化方法慢很多。盡量不要使用,apply直到沒有其他方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381286.html
上一篇:熊貓強制重新索引重復軸
