gpt4 book ai didi

python - Pandas:将多个列值一个接一个地连接起来

转载 作者:太空宇宙 更新时间:2023-11-03 21:07:52 25 4
gpt4 key购买 nike

我有这个数据框:

    0                     1
0 Bin Months Since Default
1 1 0
2 2 0< x <=6
3 3 6< x <=12
4 4 12< x <=24
5 5 24<

我想创建一个新列“texts”,它将 0 和 1 连接到另一个下面,以便生成的数据框如下所示:

    0                     1    texts
0 Bin Months Since Default Bin
1 1 0 1
2 2 0< x <=6 2
3 3 6< x <=12 3
4 4 12< x <=24 4
5 5 24< 5
6 NaN NaN Months Since Default
7 NaN NaN 0< x <=6
8 NaN NaN 6< x <=12
9 NaN NaN 12< x <=24
10 NaN NaN 24<

可能吗?

最佳答案

使用DataFrame.meltconcat :

#by all columns
s = df.melt(value_name='texts')['texts']
#if need filter columns by list
#s = df[[0,1]].melt(value_name='texts')['texts']
df = pd.concat([df, s], axis=1)
print (df)
0 1 texts
0 Bin Months Since Default Bin
1 1 0 1
2 2 0< x <=6 2
3 3 6< x <=12 3
4 4 12< x <=24 4
5 5 24< 5
6 NaN NaN Months Since Default
7 NaN NaN 0
8 NaN NaN 0< x <=6
9 NaN NaN 6< x <=12
10 NaN NaN 12< x <=24
11 NaN NaN 24<

关于python - Pandas:将多个列值一个接一个地连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55277263/

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