gpt4 book ai didi

python - 如何转置(堆叠)Dataframe 中的任意列?

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:39 25 4
gpt4 key购买 nike

我将使用此 Dataframe 作为示例:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(3, 6),
columns=['a', 'b', 'c', '2010', '2011', '2012'])

导致此数据:

          a         b         c      2010      2011      2012
0 -2.161845 -0.995818 -0.225338 0.107255 -1.114179 0.701679
1 1.083428 -1.473900 0.890769 -0.937312 0.781201 -0.043237
2 -1.187588 0.241896 0.465302 -0.194004 0.921763 -1.359859

现在我想将“2010”、“2011”和“2012”列转置(堆叠)成行以便能够获得:

        a         b         c 
-2.161845 -0.995818 -0.225338 2010 0.107255
1.083428 -1.473900 0.890769 2010 -0.937312
-1.187588 0.241896 0.465302 2010 -0.194004
-2.161845 -0.995818 -0.225338 2011 -1.114179
1.083428 -1.473900 0.890769 2011 0.781201
-1.187588 0.241896 0.465302 2011 0.921763
-2.161845 -0.995818 -0.225338 2012 0.701679
1.083428 -1.473900 0.890769 2012 -0.043237
-1.187588 0.241896 0.465302 2012 -1.359859

通过使用 df.stack(),pandas 将所有列“堆叠”成行,而我只想堆叠那些指向的列。所以我的问题是如何将任意列转置为 pandas Dataframe 中的行?

最佳答案

你应该使用 pandas.melt为此。

import numpy as np
import pandas as pd

# Note I've changed it from random numbers to integers as I
# find it easier to read and see the differences :)
df = pd.DataFrame(np.arange(18).reshape((3,6)),
columns=['a', 'b', 'c', '2010', '2011', '2012'])

var = ['a', 'b', 'c']
melted = pd.melt(df, id_vars=var)

print(melted)
# a b c variable value
# 0 0 1 2 2010 3
# 1 6 7 8 2010 9
# 2 12 13 14 2010 15
# 3 0 1 2 2011 4
# 4 6 7 8 2011 10
# 5 12 13 14 2011 16
# 6 0 1 2 2012 5
# 7 6 7 8 2012 11
# 8 12 13 14 2012 17

关于python - 如何转置(堆叠)Dataframe 中的任意列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26014025/

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