DataFrame.join
DataFrame.join(other, on=None, how=’left’, lsuffix=’’, rsuffix=’’, sort=False)
通过索引或关键列连接其他DataFrame。
传递一个列表,一次性通过索引有效的连接多个DataFrame。
Parameters
other | - DataFrame,Series,or list of DataFrame - 索引应该相同 - 如果是Series,则必须设置name属性用作生成的连接DataFrame中的列名 |
---|---|
on | 调用者的列或索引级别名称 |
how | 如何处理两个对象的操作。 - left:左连接 - right:右连接 - outer:外连接 - inner:内连接 |
lsuffix | 用于左侧连接对象重叠列的后缀 |
rsuffix | 用于右侧连接对象重叠列的后缀 |
sort | 通过连接键按字典顺序排序 |
Example
import pandas as pd
df1 = pd.DataFrame({'site': ['google', 'baidu', 'wiki'],
'age': [18, 39, 22]})
df2 = pd.DataFrame({'site': ['google', 'baidu'],
'price': [1.0, 2.0]})
df1.join(df2, lsuffix='_left', rsuffix='_right')
--------------------------------------------------------------
site_left age site_right price
0 google 18 google 1.0
1 baidu 39 baidu 2.0
2 wiki 22 NaN NaN
Example
import pandas as pd
df1 = pd.DataFrame({'site': ['google', 'baidu', 'wiki'],
'age': [18, 39, 22]})
df2 = pd.DataFrame({'site': ['google', 'baidu'],
'price': [1.0, 2.0]})
df1.set_index('site').join(df2.set_index('site'))
----------------------------------------------------------------
age price
site
google 18 1.0
baidu 39 2.0
wiki 22 NaN
Example
“join”方法总是使用“other”中的索引。
通过“on”参数使用原DataFrame中的任何列,以保留原DataFrame中的索引。
import pandas as pd
df1 = pd.DataFrame({'site': ['google', 'baidu', 'wiki'],
'age': [18, 39, 22]})
df2 = pd.DataFrame({'site': ['google', 'baidu'],
'price': [1.0, 2.0]})
df1.join(df2.set_index('site'), on='site')
-------------------------------------------------------------
site age price
0 google 18 1.0
1 baidu 39 2.0
2 wiki 22 NaN
Example
import pandas as pd
df1 = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas']})
df2 = pd.DataFrame({'count':[18, 39, 22, 45]})
df3 = pd.DataFrame({'price':[1, 2, 3, 4]})
df1.join([df2, df3])
------------------------------------------
site count price
0 google 18 1
1 baidu 39 2
2 wiki 22 3
3 pandas 45 4