合并两个熊猫数据框(在公共列上连接)
- 2025-01-20 09:07:00
- admin 原创
- 98
问题描述:
我有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)`
和
餐厅评论框架
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() 命令将这两个 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)
我对 Pandas 还很陌生,不知道在执行连接语句方面我做错了什么。
任何帮助都将非常感激。
解决方案 1:
您可以使用合并将两个数据框合并为一个:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
其中on指定要连接的两个数据框中都存在的字段名称,以及how
定义其内部/外部/左/右连接,其中 outer 使用“来自两个框架的键的并集(SQL:完全外连接)”。由于两个数据框中都有“star”列,因此默认情况下将在组合数据框中创建两列 star_x 和 star_y。正如 @DanAllan 提到的 join 方法,您可以通过将其作为 kwarg 传递来修改 merge 的后缀。默认值为suffixes=('_x', '_y')
。如果你想做类似star_restaurant_id
and 的事情star_restaurant_review
,你可以这样做:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
此链接中详细解释了这些参数。
解决方案 2:
如果 DataFrames 有一些共同的列名,则连接会失败。最简单的解决方法是包含lsuffix
orrsuffix
关键字,如下所示:
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']
。
解决方案 3:
如果有人需要尝试在索引(而不是另一列)上合并两个数据框,这也是有效的!
T1 和 T2 是具有相同索引的数据框
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
PS:我不得不使用合并,因为附加会不必要地填充 NaN。
解决方案 4:
如果您想水平合并两个 DataFrame,请使用以下代码:
df3 = pd.concat([df1, df2],axis=1, ignore_index=True, sort=False)