簡體   English   中英

根據現有列值從 pandas dataframe 中隨機選擇行子集

[英]Randomly selecting a subset of rows from a pandas dataframe based on existing column values

我有一個包含多列的 dataframe,我想根據特定列的值隨機 select 相同數量的行。 我想過使用 df.groupby['...'] 但它沒有用。 這是一個例子:

數據框

假設我想隨機 select 每個 GroupID 一行,我該如何實現? 例如,假設我 select 每個 GroupID 一個隨機行,結果將產生以下結果:

數據幀隨機選擇

這樣它就可以根據 GroupID 中的值輸出一行。 例如,假設行按 GroupID(從升序到降序)排序,然后是 select 與 GroupID 1、2、3 相關的行中的“n”行,依此類推。 任何信息肯定會有幫助。

另外,如果我需要 select 每個 GroupID 的特定行數(假設 GroupID=100 為 1 行,GroupID=200 為 4 行,等等),有什么想法嗎?

[更新] 我使用下面的推薦答案進行了小幅修改或擴展,以使用以下方法為每個組選擇性地選擇特定的 n 值:

samples = []
values = [1,  1,  2, ...]
index = 0
for group in df.GroupID.unique():
    s = df.loc[df.GroupID== group].sample(n=values[index ]).reset_index(drop=True)
    samples.append(s)
    index = index + 1
    
sample = pd.concat(samples, axis=0)

我希望這個代碼片段對你有用

samples = []
for group in df.GroupID.unique():
    s = df.loc[df.GroupID== group].sample(n=1).reset_index(drop=True)
    samples.append(s)
    
sample = pd.concat(samples, axis=0)

該代碼將從該子組中獲取每個“GroupID”和樣本觀察。 您可以連接所需樣本的子樣本(具有一個 GroupID)。

暫無
暫無

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

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