有没有一种方法可以使Pandassample
命令适应性地对列中的特定类别进行采样,同时保留其他类别中的所有值?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.sample
和concat
所有非与由反转屏蔽过滤匹配的行~
:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句