gpt4 book ai didi

python - 自动拆分并生成列

转载 作者:行者123 更新时间:2023-12-02 02:26:38 26 4
gpt4 key购买 nike

df

fruit                want_split
apple colour:red, like:yes, favourite:no
banana colour:yellow, like:yes, favourite:no
pear colour:green, like:yes, favourite:yes

有没有办法用逗号分割,然后自动生成列名,而不是手动?预期输出:

fruit                want_split                  colour      like    favourite
apple colour:red, like:yes, favourite:no red yes no
banana colour:yellow, like:yes, favourite:no yellow yes no
pear colour:green, like:yes, favourite:yes green yes yes

最佳答案

您可以在str.splitexplode之后使用pivot/unstackjoin:

u = df['want_split'].str.split(",").explode().str.split(":",expand=True)
out = df.join(u.set_index(0,append=True)[1].unstack())

print(out)

type want_split favourite like colour
0 apple colour:red, like:yes, favourite:no no yes red
1 banana colour:yellow, like:yes, favourite:no no yes yellow
2 pear colour:green, like:yes, favourite:yes yes yes green

关于python - 自动拆分并生成列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65552311/

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