pandas 熊猫附加在具有不同名称的列上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48792037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:10:49  来源:igfitidea点击:

pandas append on columns with different names

pythonpandas

提问by Yogi

How to append 2 different dataframes with different column names

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

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

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

乙

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

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

c

C

采纳答案by thesilkworm

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 concatfunction. Also best to reset indexif using this method

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

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)

回答by jpp

Outer join via pd.mergeis one way. Since this an outer join, onparameter need not be specified as pandaswill use common columns.

外连接通孔pd.merge是一种方式。由于这是一个外部连接,因此on不需要指定参数,因为pandas将使用公共列。

b = b.rename(columns={'FAM_FRUIT': 'famousfruit',
                      'FAM_ANI': 'famousanimal',
                      'cid': 'countryid'})

a.merge(b, how='outer')

#    countryid famousanimal famousfruit  waterlvl
# 0         22       monkey      banana      23.0
# 1         36     elephant       apple      43.0
# 2         21       monkey       mango      41.0
# 3         64        horse      orange      87.0
# 4         25      giraffe      grapes       NaN
# 5         27          dog   pineapple       NaN
# 6         98          cat     avacado       NaN
# 7         67        horse      orange       NaN