pandas 附加在具有不同名称的列上 [英] pandas append on columns with different names

查看:43
本文介绍了 pandas 附加在具有不同名称的列上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何附加具有不同列名的 2 个不同的数据框

How to append 2 different dataframes with different column names

a = pd.DataFrame({
    "id": [0,1,2,3],
    "countryid": [22,36,21,64],
    "famousfruit": ["banana", "apple", "mango", "orange"],
    "famousanimal": ["monkey", "elephant", "monkey", "horse"],
    "waterlvl": [23, 43, 41, 87]
}).set_index("id")

>> a

b = pd.DataFrame({
    "id": [0,1,2,3],
    "cid": [25,27,98,67],
    "FAM_FRUIT": ["grapes", "pineapple", "avacado", "orange"],
    "FAM_ANI": ["giraffe", "dog", "cat", "horse"],
}).set_index("id")

>>b

如何将 b 上的行附加到各自的列(其名称与 a 相比不同)并产生如下所示的结果 c

How to append the rows on b on the respective columns(whose names are different compared to a) and produce a result like below c

推荐答案

我能想到的最简单的方法是简单地重命名 b 中的列以匹配 a 中的列,然后使用 Pandas concat 函数.如果使用这个,最好也重置索引方法

Easiest way I can think of to do this is to simply rename the columns in b to match those in a, then use the Pandas concat function. Also best to reset index if using this method

b.rename(columns={'FAM_FRUIT': 'famousfruit',
                 'FAM_ANI': 'famousanimal',
                 'cid': 'countryid'}, inplace=True)
a = pd.concat([a, b])
a.reset_index(inplace=True, drop=True)

这篇关于 pandas 附加在具有不同名称的列上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆