gpt4 book ai didi

python - 使用 Pandas 替换不同列的元素

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:00 26 4
gpt4 key购买 nike

我有 2 个这样的数据框列:

df1 = pd.DataFrame({'A':['CINO','KONO','ROLO','MANE','TUTU']})
df2 = pd.DataFrame({'B':['NION','PONO','RZCO','MPPE','TQAS']})

我的想法是以输出如下所示的方式组合数据帧:

        C
CC1 CINO <---- belongs to A
CC1 NION <---- belongs to B
CC2 KONO <---- belongs to A
CC2 PONO <---- belongs to B
CC3 ROLO <---- belongs to A
CC3 RZCO <---- belongs to B
CC4 MANE <---- belongs to A
CC4 MPPE <---- belongs to B
CC5 TUTU <---- belongs to A
CC5 TQAS <---- belongs to B

如您所见,B 列的项目放置在 A 列的行之间。请注意行的命名方式,每对行都具有相同的名称。

你能建议我使用一些内置的 Pandas 函数来实现这个目标吗?

最佳答案

pd.concat(
[df1, df2], axis=1
).stack().reset_index(1, drop=True).to_frame('C').rename(index='CC{}'.format)

C
CC0 CINO
CC0 NION
CC1 KONO
CC1 PONO
CC2 ROLO
CC2 RZCO
CC3 MANE
CC3 MPPE
CC4 TUTU
CC4 TQAS

关于python - 使用 Pandas 替换不同列的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41808772/

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