ano*_*428 67 python merge left-join dataframe 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)`
Run Code Online (Sandbox Code Playgroud)
和
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)
Run Code Online (Sandbox Code Playgroud)
我想加入这两个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')
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这个时,我收到以下错误:
Exception: columns overlap: Index([business_id, stars, type], dtype=object)
Run Code Online (Sandbox Code Playgroud)
我对pandas很新,并且不知道我在执行join语句时遇到了什么问题.
任何帮助将非常感激.
mli*_*imb 96
您可以使用merge将两个数据帧合并为一个:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
Run Code Online (Sandbox Code Playgroud)
where on指定存在于要连接的两个数据帧中的字段名称,以及如何
定义其内部/外部/左/右连接,外部使用"来自两个帧的键的并集(SQL:完全外部连接)".由于两个数据框中都有"星标"列,因此默认情况下会在合并后的数据框中创建两列star_x和star_y.正如@DanAllan为join方法所提到的,您可以通过将其作为kwarg传递来修改merge的后缀.默认是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'))
Run Code Online (Sandbox Code Playgroud)
这个参数在这个链接中有详细解释.
Dan*_*lan 18
如果DataFrame具有一些共同的列名,则加入失败.最简单的方法是包含一个lsuffix或rsuffix类似的关键字:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
Run Code Online (Sandbox Code Playgroud)
这样,列具有不同的名称.该文档解决了这个问题.
或者,您可以通过在加入之前删除违规列来解决这个问题.例如,如果星星中的星星restaurant_ids_dataframe多余restaurant_review_frame,那么你可以del restaurant_ids_dataframe['stars'].
Fir*_*ras 12
如果有人需要尝试在索引(而不是另一列)上合并两个数据帧,这也有效!
T1和T2是具有相同索引的数据帧
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
Run Code Online (Sandbox Code Playgroud)
PS我必须使用merge,因为append将不必要地填充NaN.
| 归档时间: |
|
| 查看次数: |
140699 次 |
| 最近记录: |