簡體   English   中英

Python數據框:隨機排列行

[英]Python Dataframe: Shuffle group of rows

混洗數據幀中的一組行的最佳方法是什么? 需要這個用於改組模型的火車。

例如,每隔10行作為一個單獨的組進行洗牌,或者具有某種邏輯條件以創建單獨的組並將它們作為一個組洗牌。

如果使用要分組的索引創建新列,則可以執行以下操作:

groups = [df.sample(frac=1) for _, df in df.groupby('index_to_group_on')]
return pandas.concat(groups)

例如,如果您想隨機播放每組10行,可以通過以下方式創建此索引:

df['group_of_ten'] = numpy.arange(len(df)/10)

如果您要進行交叉驗證,則可以查看scikit-learn的train_test_splithttp : train_test_split

也可能有其他方法,一種方法可能是使用sklearn shuffle 您可以對要混排的n行進行切片,並使用.append append剩余的其他行到.append的結果中。

from sklearn.utils import shuffle

# if df is the dataframe to then:
n = 10 # number of rows to shuffle
shuffled_df = shuffle(df[:n]).append(df[n:])

您可以做的是-創建一個標識組的列,然后按該列分組,然后隨機分組每個組。

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df['group_id'] = np.arange(df.shape[0]) // 10  # // is integer division in python3, won't work in python2
shuffled_groups = [v.drop(['group_id'], axis=1).sample(frac=1).reset_index(drop=True) for k, v in df.groupby('group_id')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM