107

私は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)

pandas の DataFrame.join() コマンドを使用して、これら 2 つの DataFrame を結合して単一のデータフレームにしたいと考えています。

次のコード行を試しました。

#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)

私はパンダに非常に慣れていないため、結合ステートメントの実行に関する限り、何が間違っているのかわかりません。

どんな助けでも大歓迎です。

4

3 に答える 3

154

マージを使用して、2 つのデータフレームを 1 つに結合できます。

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

where onは、結合する両方のデータフレームに存在するフィールド名を指定し、how は、「両方のフレームからのキーの結合 (SQL: 完全外部結合)」を使用して、その内部/外部/左/右の結合を定義します。両方のデータフレームに「スター」列があるため、デフォルトでは、結合されたデータフレームに star_x と star_y の 2 つの列が作成されます。@DanAllan が join メソッドについて言及したように、マージのサフィックスを 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'))

パラメータについては、このリンクで詳しく説明されています。

于 2013-09-14T08:11:16.573 に答える
26

DataFrame に共通の列名がある場合、結合は失敗します。これを回避する最も簡単な方法は、次のようにlsuffixorrsuffixキーワードを含めることです。

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'].

于 2013-09-13T18:39:35.600 に答える