gpt4 book ai didi

python - Pandas 追加在具有不同名称的列上

转载 作者:行者123 更新时间:2023-11-28 21:00:12 25 4
gpt4 key购买 nike

如何附加 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

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

c

最佳答案

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

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)

关于python - Pandas 追加在具有不同名称的列上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48792037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com