我正在使用一個數據集,該數據集的第一列中包含情感或類別標簽。但是,由于數據集不平衡,我需要為每個類別提取相同數量的行。也就是說,如果有 10 個類別,我只需從每個類別中選擇 100 行樣本。結果將是 1000 行樣本。我嘗試過的:def append_new_rows(df, new_df, s): c = 0 for index, row in df.iterrows(): if s == row[0]: if c <= 100: new_df.append(row) c += 1 return df_2for s in sorted(list(set(df.category))): new_df = append_new_rows(df, new_df, s)數據集----------------------------| category | A | B | C | D |----------------------------| happy | ...| ...|...|...|| ... | ...| ...|...|...|| sadness | ...| ...|...|...|預期產出----------------------------| category | A | B | C | D |----------------------------| happy | ...| ...|...|...|... 100 samples of happy| ... | ...| ...|...|...|| sadness | ...| ...|...|...|... 100 samples of sadness......1000 sampple rows
1 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
def append_new_df(df, df_2, s, n):
c = 1
for index, row in df.iterrows():
if s == row[0]:
if c <= n:
df_2 = df_2.append(row)
c += 1
return df_2
你就在那里,你只需要做這樣的事情
添加回答
舉報
0/150
提交
取消