아래와 같은 두 개의 데이터 프레임이 있습니다. pandas와 numpy를 사용하여 차이점을 비교합니다.
df_a
Key Value
0 data_owner John
1 locationcode local
2 Unit sales
3 application autosales
df_b
Key Value
0 data_owner John
1 locationcode local
2 Unit sales
3 application autosales
4 department frontoffice
병합을 위해 아래 코드를 사용하고 있습니다.
df = pd.merge(df_a,df_b,on=['Key'],how='outer',left_index=True,right_index=True)
df['diff'] = np.where((df['Value_x']==df['Value_y']), 'No', 'Yes')
출력하려는 의도는 df와 양쪽의 누락 된 항목을 모두 비교하여 출력해야합니다.
아래의 실제 출력 :하지만 문제는 두 데이터 프레임의 키를 표시하고 싶지만 아래 출력이 한 번만 표시되는 것을 보면 출력의 일부가되기 위해 Key_y도 필요합니다.
Key Value_x Value_y diff
0 data_owner John John No
1 locationcode local local No
2 unit sales sales No
3 application autosales autosales No
4 department frontoffice NaN No
예상 출력 : 둘 다에서 키를 표시하고 싶었습니다.
Key_x Value_x Key_y Value_y diff
0 data_owner John data_owner John No
1 locationcode local locationcode local No
2 unit sales unit sales No
3 application autosales application autosales No
4 department frontoffice NaN NaN Yes
사용은, DataFrame.add_suffix
그들을 병합하기 전에 모두 dataframes의 컬럼에 접미사를 추가하려면, 자신의 키를 병합 한 후 하나의 컬럼에 결합하지 않습니다이 방법 :
df = pd.merge(
df_b.add_suffix('_x'), df_a.add_suffix('_y'),
left_on='Key_x', right_on='Key_y', how='outer')
df['diff'] = np.where(df['Value_x'].eq(df['Value_y']), 'No', 'Yes')
# print(df)
Key_x Value_x Key_y Value_y diff
0 data_owner John data_owner John No
1 locationcode local locationcode local No
2 Unit sales Unit sales No
3 application autosales application autosales No
4 department frontoffice NaN NaN Yes
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다