2017-03-19 136 views
1

熊貓數據幀改組值熊貓數據幀

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

預期輸出的列(重新洗牌後)

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

如圖所示,我希望改組(索引,值)整個對,但想要重新洗牌列中的值(colA中的重新洗牌值將具有新的索引)

是否有任何知道如何做到這一點?

在此先感謝!

回答

1

也許,最簡單的方法是使用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 

然後

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

np.shuffle到位工作。

np.random.shuffle(df.colA) 

將洗牌在colA
值的陣列來檢查

df 

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