gpt4 book ai didi

python - Pandas 根据条件转置

转载 作者:行者123 更新时间:2023-12-05 08:48:00 25 4
gpt4 key购买 nike

我有一个数据框

Key   Col1 Col2 Col3   Colother
1 11 12 0 'a'
2 0 21 31 'b'
3 5 6 7 'c'

预期输出

Key   Col1 Col2 Col3   Colother  Colnew
1 11 12 0 'a' 11
1 11 12 0 'a' 12
2 0 21 31 'b' 21
2 0 21 31 'b' 31
3 5 6 7 'c' 5
3 5 6 7 'c' 6
3 5 6 7 'c' 7

我尝试过使用 df.T 但它的选项有限。因为我不想为 0 列创建行。现在我只剩下遍历行了。

最佳答案

尝试使用 agg 然后使用 explode

df['Colnew'] = df[['Col1','Col2','Col3']].agg(list,1)
df = df.explode('Colnew').loc[lambda x : x['Colnew']!=0]
df
Out[364]:
Key Col1 Col2 Col3 Colother Colnew
0 1 11 12 0 'a' 11
0 1 11 12 0 'a' 12
1 2 0 21 31 'b' 21
1 2 0 21 31 'b' 31
2 3 5 6 7 'c' 5
2 3 5 6 7 'c' 6
2 3 5 6 7 'c' 7

关于python - Pandas 根据条件转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66692098/

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