해결 방법: 개체와 int64 열을 병합하려고 합니다.
pandas를 사용할 때 발생할 수 있는 오류는 다음과 같습니다.
ValueError : You are trying to merge on int64 and object columns.
If you wish to proceed you should use pd.concat
이 오류는 두 개의 Pandas DataFrame을 병합하려고 하는데 병합하려는 열이 한 DataFrame의 개체이고 다른 DataFrame의 정수일 때 발생합니다.
다음 예에서는 실제로 이 오류를 수정하는 방법을 보여줍니다.
오류를 재현하는 방법
다음 두 개의 Panda DataFrame을 생성한다고 가정해 보겠습니다.
import pandas as pd #createDataFrame df1 = pd. DataFrame ({' year ': [2015, 2016, 2017, 2018, 2019, 2020, 2021], ' sales ': [500, 534, 564, 671, 700, 840, 810]}) df2 = pd. DataFrame ({' year ': ['2015', '2016', '2017', '2018', '2019', '2020', '2021'], ' refunds ': [31, 36, 40, 40, 43, 70, 62]}) #view DataFrames print (df1) year sales 0 2015 500 1 2016 534 2 2017 564 3 2018 671 4 2019 700 5,2020 840 6 2021 810 print (df2) year refunds 0 2015 31 1 2016 36 2 2017 40 3 2018 40 4 2019 43 5 2020 70 6 2021 62
이제 두 DataFrame을 병합하려고 한다고 가정합니다.
#attempt to merge two DataFrames
big_df = df1. merge (df2, on=' year ', how=' left ')
ValueError : You are trying to merge on int64 and object columns.
If you wish to proceed you should use pd.concat
첫 번째 DataFrame의 연도 변수는 정수이지만 두 번째 DataFrame의 연도 변수는 객체이기 때문에 ValueError가 발생합니다.
오류를 수정하는 방법
이 오류를 해결하는 가장 쉬운 방법은 두 번째 DataFrame의 연도 변수를 정수로 변환한 다음 병합을 수행하는 것입니다.
다음 구문은 이를 수행하는 방법을 보여줍니다.
#convert year variable in df2 to integer
df2[' year ']=df2[' year ']. astype (int)
#merge two DataFrames
big_df = df1. merge (df2, on=' year ', how=' left ')
#view merged DataFrame
big_df
year sales refunds
0 2015 500 31
1 2016 534 36
2 2017 564 40
3 2018 671 40
4 2019 700 43
5 2020 840 70
6 2021 810 62
ValueError 는 전혀 수신되지 않았으며 두 DataFrame을 하나로 성공적으로 병합했습니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
수정방법: 열이 겹치는데 접미사가 지정되지 않음
수정 방법: ‘numpy.ndarray’ 개체에 ‘append’ 속성이 없습니다.
해결 방법: 모든 스칼라 값을 사용하는 경우 인덱스를 전달해야 합니다.