用 Python 编写一个程序以根据列中的匹配数据合并两个数据框
假设你有两个数据框
first dataframe is id 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
解决方案
为此,我们将按照以下给定的步骤进行操作 -
定义两个数据框
根据定义的相同列 id 合并两个数据框如下
pd.merge(first_df,second_df,how='inner',on='id')
示例
让我们看看以下实现以获得更好的理解 -
import pandas as pd import 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 is id 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
广告