[python] 두 개의 Pandas 데이터 프레임 결합 (공통 열에 결합)

2 개의 데이터 프레임이 있습니다.

restaurant_ids_dataframe

Data columns (total 13 columns):
business_id      4503  non-null values
categories       4503  non-null values
city             4503  non-null values
full_address     4503  non-null values
latitude         4503  non-null values
longitude        4503  non-null values
name             4503  non-null values
neighborhoods    4503  non-null values
open             4503  non-null values
review_count     4503  non-null values
stars            4503  non-null values
state            4503  non-null values
type             4503  non-null values
dtypes: bool(1), float64(3), int64(1), object(8)`

restaurant_review_frame

Int64Index: 158430 entries, 0 to 229905
Data columns (total 8 columns):
business_id    158430  non-null values
date           158430  non-null values
review_id      158430  non-null values
stars          158430  non-null values
text           158430  non-null values
type           158430  non-null values
user_id        158430  non-null values
votes          158430  non-null values
dtypes: int64(1), object(7)

이 두 DataFrame을 결합하여 pandas의 DataFrame.join () 명령을 사용하여 단일 데이터 프레임으로 만들고 싶습니다.

다음 코드 줄을 시도했습니다.

#the following line of code creates a left join of restaurant_ids_frame and   restaurant_review_frame on the column 'business_id'
restaurant_review_frame.join(other=restaurant_ids_dataframe,on='business_id',how='left')

그러나 이것을 시도하면 다음과 같은 오류가 발생합니다.

Exception: columns overlap: Index([business_id, stars, type], dtype=object)

나는 pandas를 처음 접했고 join 문을 실행하는 한 내가 뭘 잘못하고 있는지 전혀 알지 못합니다.

어떤 도움을 주시면 감사하겠습니다.



답변

병합 을 사용 하여 두 개의 데이터 프레임을 하나로 결합 할 수 있습니다 .

import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')

여기서 on 은 조인 할 두 데이터 프레임에 존재하는 필드 이름을 지정
하고 내부 / 외부 / 왼쪽 / 오른쪽 조인 여부를 ‘두 프레임의 키 조합 (SQL : 전체 외부 조인)’을 사용하는 외부와 함께 정의 하는 방법을 지정 합니다. 두 데이터 프레임에 ‘star’열이 있으므로 기본적으로 결합 된 데이터 프레임에 두 개의 열 star_x 및 star_y가 생성됩니다. @DanAllan이 조인 메서드에 대해 언급했듯이 kwarg로 전달하여 병합 할 접미사를 수정할 수 있습니다. 기본값은 suffixes=('_x', '_y')입니다. star_restaurant_id및 같은 작업을 수행하려면 다음을 수행 star_restaurant_review할 수 있습니다.

 pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))

매개 변수는이 링크 에 자세히 설명되어 있습니다.


답변

DataFrames에 공통적 인 열 이름이 있으면 조인이 실패합니다. 가장 간단한 방법은 다음 과 같이 lsuffix또는 rsuffix키워드 를 포함하는 것입니다 .

restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")

이렇게하면 열에 고유 한 이름이 있습니다. 문서는 바로이 문제를 다룹니다 .

또는 가입하기 전에 문제가되는 열을 삭제하여이 문제를 해결할 수 있습니다. 예를 들면, 별, 경우 restaurant_ids_dataframe의 별을 중복 restaurant_review_frame, 당신은 할 수 있었다 del restaurant_ids_dataframe['stars'].


답변

누군가가 인덱스에서 (다른 열 대신) 두 개의 데이터 프레임을 함께 병합해야하는 경우에도 작동합니다!

T1과 T2는 동일한 인덱스를 가진 데이터 프레임입니다.

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

추신 : append가 불필요하게 NaN을 채울 것이기 때문에 merge를 사용해야했습니다.


답변