python - 合并两个 pandas 数据框(加入一个公共(public)列)

标签 python pandas dataframe merge left-join

我有 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() 命令将这两个 DataFrame 连接成一个单独的 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 很陌生,就执行 join 语句而言,我不知道我做错了什么。

任何帮助将不胜感激。

最佳答案

您可以使用 merge 将两个数据框合并为一个:

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

on 指定两个数据帧中存在的字段名称以加入,以及如何 定义是否它的内部/外部/左/右连接,外部使用“来自两个框架的键的联合(SQL:完全外部连接)。”由于您在两个数据框中都有“星”列,因此默认情况下,这将在组合数据框中创建两列 star_x 和 star_y。正如@DanAllan 提到的 join 方法,您可以通过将其作为 kwarg 传递来修改合并的后缀。默认为 suffixes=('_x', '_y')。如果你想做 star_restaurant_idstar_restaurant_review 之类的东西,你可以这样做:

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

参数在这篇link中有详细解释.

关于python - 合并两个 pandas 数据框(加入一个公共(public)列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18792918/

相关文章:

python - 如何计算数据框中一行的增加/减少数量

r - 如何在日期不进行类型转换的情况下将列表转换为数据框

python-3.x - 如何从Python数组创建对象

python - 为什么 Pandas 在访问具有列和索引值的 DataFrame 时不返回标量/字符串而不是系列?

python - 根据其他数据帧的条件创建数据帧

scala - 使用 Spark DataFrame 获取列上的不同值

python - 如何解决此 python 代码中缺少 1 个必需的位置参数?

python - 为什么 plt.show() 显示一个额外的空白数字

python - 如何在 TravisCI 上添加 NLTK 'wordnet' ?

python sys.stdin.read() 来自 tail -f