【问题标题】:Shuffle pandas columns洗牌熊猫列
【发布时间】:2020-05-05 10:40:38
【问题描述】:

我有以下数据框:

    Col1  Col2  Col3  Type
0      1     2     3     1
1      4     5     6     1
2      7     8     9     2

我想要一个像这样的洗牌输出:

        Col3  Col1  Col2  Type
    0      3     1     2     1
    1      6     4     5     1
    2      9     7     8     2

如何做到这一点?

【问题讨论】:

    标签: python-3.x pandas shuffle


    【解决方案1】:

    DataFrame.sampleaxis=1 一起使用:

    df = df.sample(frac=1, axis=1)
    

    如果需要最后一列不改变位置:

    a = df.columns[:-1].to_numpy()
    np.random.shuffle(a)
    print (a)
    ['Col3' 'Col1' 'Col2']
    
    df = df[np.append(a, ['Type'])]
    print (df)
       Col2  Col3  Col1  Type
    0     3     1     2     1
    1     6     4     5     1
    2     9     7     8     2
    

    【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2017-08-10
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多