[英]What is the best way to shuffle/permute each n rows of a data frame in python?
我想隨機播放數據框的每個 n (窗口大小)行,但我不確定如何以 pythonic 方式進行。 我找到了洗牌所有行的答案,但沒有找到給定 window 大小的答案:
def permute(df: pd.DataFrame, window_size: int = 10) -> pd.DataFrame:
df_permuted = df.copy()
"""How would you shuffle every window_size rows for the modifiable columns?"""
df_permuted.loc[:, modifiable_columns]
...
return df_permuted
此代碼定義了一個名為 permute 的 function,它接受 Pandas dataframe 和 window 大小(默認設置為 10)並返回一個新的 dataframe 已經洗牌。
function首先通過輸入dataframe的長度除以window的大小計算出windows的個數。 然后它遍歷 windows 並使用 dataframe 的采樣方法對每個 window 中的行進行隨機排序,隨機重新排序行。 最后,它使用 concat 方法將所有打亂后的 windows 連接成一個 dataframe 並返回這個 dataframe。
然后,代碼通過創建一個小的 dataframe 並將其打印出來來測試排列 function,然后使用大小為 3 的 window 調用排列 function 並打印出洗牌后的 dataframe。
import pandas as pd
def permute(df: pd.DataFrame, window_size: int = 10) -> pd.DataFrame:
num_windows = len(df) // window_size
compil = []
for i in range(num_windows):
start = i * window_size
end = (i+1) * window_size
compil.append( df.iloc[start:end].sample(frac=1))
df = pd.concat(compil)
return df
# Test the permute function
df = pd.DataFrame({"A": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"B": [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]})
print(df)
df_permuted = permute(df, window_size=3)
print(df_permuted)
output:
A B
0 1 11
1 2 12
2 3 13
3 4 14
4 5 15
5 6 16
6 7 17
7 8 18
8 9 19
9 10 20
A B
2 3 13
0 1 11
1 2 12
5 6 16
3 4 14
4 5 15
6 7 17
8 9 19
7 8 18
接受的答案未矢量化。 使用groupby.sample
是更好的選擇:
df.groupby(np.arange(len(df))//N).sample(frac=1)
要添加代碼注釋中的附加要求,但不在您的問題中,這里有一個版本也考慮了可修改的列。
在下面的示例中, mod
和mod2
是您可以修改的列,而nomod
列是不可修改的。
我相信使用矢量化方法無法實現可修改的列,並添加到已接受的答案中。 此外,接受的答案在 memory 中保留了整個 df 的另一個完整表示,而我的版本只保留了 memory 與window_size
一樣大的記錄。
df = pd.DataFrame([np.arange(0, 12)]*3).T
df.columns = ['mod', 'nomod', 'mod2']
df
mod nomod mod2
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
9 9 9 9
10 10 10 10
11 11 11 11
def permute(df, window_size, modifiable_columns):
num_chunks = int(len(df) / window_size)
for i in range(0, num_chunks):
start_ind = i * window_size
end_ind = i * window_size + window_size
df_row_subset = df.loc[start_ind:end_ind-1, modifiable_columns].sample(frac=1, random_state=1)
df_row_subset.index = np.arange(start_ind, end_ind)
df.loc[df_row_subset.index, modifiable_columns] = df_row_subset
return df
permute(df, 4, ['mod', 'mod2'])
mod nomod mod2
0 3 0 3
1 2 1 2
2 0 2 0
3 1 3 1
4 7 4 7
5 6 5 6
6 4 6 4
7 5 7 5
8 11 8 11
9 10 9 10
10 8 10 8
11 9 11 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.