如何在pandas中合并两个或多个数据框?

3

我正在尝试将三个数据框连接起来,但是遇到了一些问题。让我展示一下场景。

我有三个数据框:

第一个数据框: Country(国家)

只有两列:Country_ID(国家编号),Country_Name(国家名称) 主键:Country_ID(国家编号)

Country_ID(国家编号) | Country_Name(国家名称)

BR     |   Brazil

第二点: 体育

只需要三列:国家ID,运动项目ID,运动项目名称 主键:国家ID,运动项目ID

国家ID | 运动项目ID| 运动项目名称

BR         |    1234     |     Football

第三步: 大学

只有四列: 国家ID,大学ID,大学名称 主键: 国家ID,大学ID

国家ID | 大学ID| 大学名称

BR         |    UFCABC        | Federal University of ABC

最终结果:仅包括这些列:国家名称,运动项目名称,大学名称

国家名称 | 运动项目名称 | 大学名称

Brazil | Football | 巴西联邦大学

我尝试加入CountryXSport数据框,然后再与university数据框连接,但是我做不到。

以下是创建和连接数据框的代码:

country_raw_data = {
            'country_id': [country.id for country in countries],
            'country_name': [country.name for country in countries]                                  }

sport_raw_data = {
            'country_id': [sport.country.id for sport in sports],                
            'sport_id': [sport.id for sport in sports],
            'sport_name': [sport.name for sport in sports]
        }

university_raw_data = {
            'country_id': [university.country.id for university in universities],                
            'university_id': [university.state.id for university in universities],
            'university_name': [university.name for university in universities]
        }

现在,数据框实例:
我尝试像这样创建数据框:
country_df = pd.DataFrame(country_raw_data, columns: ['country_id', 'country_name'])

我不知道为什么,country_df创建错误,一些列并没有正确显示相应的值。然后我按照下面的方法创建,现在它可以工作了。
country_df = pd.DataFrame(country_raw_data) 
sport_df = pd.DataFrame(sport_raw_data) 
university_df = pd.DataFrame(university_raw_data) 

这里是关于连接声明:

我尝试过像这样做,但结果连接不正确。有些列没有正确地包含在数据框中。

country_state_df = pd.merge(country_df, state_df, on='country_id', how='inner')

我曾经写过另一段代码,但是我之前也遇到了同样的问题:

country_sport_df = pd.merge(country_df, sport_df, 
                        left_on='country_id', 
                        right_on='sport_id', 
                        how='inner')

所以,第一个连接后,我对country_state和city进行了下一个连接。

country_sport_university.df = pd.merge(country_sport_df, university_df, 
                             on=['country_id', 'country_id'], 
                             how='inner')

我希望最终结果类似这些列:
国家名称 | 运动名称 | 大学名称
巴西 | 足球 | ABC联邦大学
使用数据框架可以实现吗,还是需要使用其他库?
因此,有很多数据,大约有数百万条数据。
有人能帮助我或给我解决问题的建议吗?
非常感谢!

你能否提供一个可重现的例子,包括你的三个数据框?你可以附上 country_df.head(5) 和其他的。 - Anton Protopopov
1个回答

3

您应该能够:

country_sport_df = country_df.merge(sport_df, on='country_id', how='inner')
country_university_df = university_df.merge(sport_df, on='country_id', how='inner').drop(['country_id', 'sport_id', 'university_id'], axis=1)

我假设 country_idsport_iduniversity_id 之间唯一的联系。该设计意在如此。

我没有意识到你可以链式删除。这会防止常见列的后缀吗? - trench
Stefan,谢谢你的帮助。现在它可以工作了。我找到了一份关于此的好文档:链接 - Kadu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接