gpt4 book ai didi

python - 有选择地对 pandas 中的特定类别进行采样

转载 作者:行者123 更新时间:2023-12-01 06:49:12 26 4
gpt4 key购买 nike

是否有一种方法可以使 Pandas sample 命令有选择地对列中的特定类别进行采样,同时保留其他类别中的所有值? https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html

例如在下面的数据框中,我想对数据框中的一半 Poor Observed_Condition 行进行采样,但保留具有 Good 或 Excellent 值的所有 Observed_Condition 行:

Predicted   Observed_Condition
4.561074719 Excellent
3.114821134 Poor
5.47200407 Good
7.048857494 Excellent
5.318448093 Poor
3.81681577 Poor
5.640660645 Good
3.082072075 Good
3.249229815 Poor
4.492327775 Good
3.488655803 Poor
6.517144589 Good

最佳答案

使用boolean indexing要按条件过滤,请添加 DataFrame.sampleconcat所有不匹配的行均通过 ~ 的反向掩码进行过滤:

mask = df['Observed_Condition'] == 'Poor'

df = pd.concat([df[mask].sample(frac=0.5), df[~mask]]).sort_index()
print (df)
Predicted Observed_Condition
0 4.561075 Excellent
2 5.472004 Good
3 7.048857 Excellent
4 5.318448 Poor
6 5.640661 Good
7 3.082072 Good
8 3.249230 Poor
9 4.492328 Good
11 6.517145 Good

关于python - 有选择地对 pandas 中的特定类别进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102560/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com