简体   繁体   English

在熊猫数据框的列中重新洗牌

[英]Reshuffle values in columns of panda dataframe

Panda dataframe 熊猫数据框

|   | col A |   
|---|-------|
| 0 | A     |   
| 1 | B     |  
| 2 | C     |

Expected output (After re-shuffling) 预期输出(重新洗牌后)

|   | col A |   
|---|-------|
| 0 | B     |   
| 1 | C     |  
| 2 | A     |

As shown, I do not want to reshuffle the (index,value) entire pair but want to reshuffle the values in the columns (after reshuffling values in colA will have new index) 如图所示,我不想洗牌(指数值)全对,但想洗牌的列中的值(可乐洗牌值后,将会有新的指数)

Does any know how to do this? 有谁知道怎么做?

Thanks in advance! 提前致谢!

np.shuffle operates in place. np.shuffle在原地运作。

np.random.shuffle(df.colA)

will shuffle the array of values in colA colA的值数组
to check 去检查

df

  colA
0    C
1    E
2    A
3    F
4    D
5    B

Probably, the easiest way is to use np.random.permutation 可能最简单的方法是使用np.random.permutation

>>> import pandas as pd, numpy as np
>>> df = pd.DataFrame({'colA':list('ABCDEF')})
>>> df
  colA
0    A
1    B
2    C
3    D
4    E
5    F

Then 然后

>>> df['colA'] = np.random.permutation(df.colA)
>>> df
  colA
0    D
1    A
2    F
3    B
4    C
5    E
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM