用Python编写程序以基于列中的匹配数据合并两个数据框
假设您有两个数据框,
first dataframe isid country
0 1 India
1 2 UK
2 3 US
3 4 China
second dataframe is
id City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu
并且基于同一列进行合并的结果是,
Merging data based on same column - idid country City
0 1 India Chennai
1 4 China Chengdu
解决方案
为了解决这个问题,我们将遵循以下步骤-
定义两个数据框
下面定义了基于相同列ID的两个数据框的合并,
pd.merge(first_df,second_df,how='inner',on='id')
例子
让我们看下面的实现以更好地理解-
import pandas as pdimport numpy as np
first_df = pd.DataFrame({'id':[1,2,3,4], 'country':['India','UK','US','China']})
print("first dataframe is\n", first_df)
second_df = pd.DataFrame({'id':[1,11,22,4],'City' :['Chennai','Cambridge','Chicago','Chengdu']})
print("second dataframe is\n", second_df)
print("Merging data based on same column - id")
print(pd.merge(first_df,second_df,how='inner',on='id'))
输出
first dataframe isid country
0 1 India
1 2 UK
2 3 US
3 4 China
second dataframe is
id City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu
Merging data based on same column - id
id country City
0 1 India Chennai
1 4 China Chengdu
以上是 用Python编写程序以基于列中的匹配数据合并两个数据框 的全部内容, 来源链接: utcz.com/z/329772.html