[英]Shuffle rows of dataframe based on a condition
我有一個包含 ID 列的數據框,我想對只有特定 ID 的行進行洗牌。
我的數據框的一個例子是:
-------------------------------
ID | Fruit | Color
-------------------------------
1 apple green
2 orange orange
1 pear green
2 grapefruit yellow
1 banana yellow
2 tomato red
1 grape black
2 melon yellow
而不是混洗整個數據幀,我到目前為止已經用df.sample(frac=1)
,我試圖弄清楚如何只混洗 ID=1 的那些數據幀。 我試過下面的,它產生了一個語法錯誤。
df.apply(lambda x: df.sample(frac=1) if x['ID'] == 1)
想法是通過帶有boolean indexing
的掩碼過濾行,獲取sample
並將轉換值分配回numpy數組以防止索引對齊:
m = df['ID'] == 1
df[m] = df[m].sample(frac=1).to_numpy()
#oldier pandas versions
#df[m] = df[m].sample(frac=1).values
print (df)
ID Fruit Color
0 1 pear green
1 2 orange orange
2 1 grape black
3 2 grapefruit yellow
4 1 apple green
5 2 tomato red
6 1 banana yellow
7 2 melon yellow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.