我有一个pandas数据帧,该数据帧具有不同数量的整数,并且每行中有NaNs
。我想将每行中的值分配为8个bin-每行4个bin负值和4个正面值。因此,每行每个bin中将有不同数量的值。关于如何调整qcut
功能的任何提示?谢谢!
答案 0 :(得分:0)
如果我理解正确,您可以对正值进行qcut
,对负值进行qcut
。
例如,给定数据框:
>>> df
vals
0 -0.456460
1 0.448368
2 0.186750
3 1.056617
4 -0.035620
5 -0.609843
6 0.126376
7 0.160817
8 -1.495441
9 0.730763
10 -0.005071
11 0.677918
12 -0.779553
13 0.717374
14 2.250258
15 -0.801028
16 0.306408
17 0.538970
18 -2.120528
19 1.066903
使用2 qcuts
,一个为正,另一个为负。
df.loc[df.vals > 0,'bin'] = pd.qcut(df.loc[df.vals > 0,'vals'], q=4)
df.loc[df.vals < 0,'bin'] = pd.qcut(df.loc[df.vals < 0,'vals'], q=4)
因此,它们被分为8个唯一的bin,其中4个为正,4个为负:
>>> df
vals bin
0 -0.456460 (-0.695, -0.351]
1 0.448368 (0.276, 0.608]
2 0.186750 (0.125, 0.276]
3 1.056617 (0.812, 2.25]
4 -0.035620 (-0.351, -0.00507]
5 -0.609843 (-0.695, -0.351]
6 0.126376 (0.125, 0.276]
7 0.160817 (0.125, 0.276]
8 -1.495441 (-2.122, -0.975]
9 0.730763 (0.608, 0.812]
10 -0.005071 (-0.351, -0.00507]
11 0.677918 (0.608, 0.812]
12 -0.779553 (-0.975, -0.695]
13 0.717374 (0.608, 0.812]
14 2.250258 (0.812, 2.25]
15 -0.801028 (-0.975, -0.695]
16 0.306408 (0.276, 0.608]
17 0.538970 (0.276, 0.608]
18 -2.120528 (-2.122, -0.975]
19 1.066903 (0.812, 2.25]
您可以对垃圾箱进行排序以使其可视化,这样您就可以看到4个正值箱和4个负值箱:
np.sort(df['bin'].unique())
array([Interval(-2.1219999999999999, -0.97499999999999998, closed='right'),
Interval(-0.97499999999999998, -0.69499999999999995, closed='right'),
Interval(-0.69499999999999995, -0.35099999999999998, closed='right'),
Interval(-0.35099999999999998, -0.0050699999999999999, closed='right'),
Interval(0.125, 0.27600000000000002, closed='right'),
Interval(0.27600000000000002, 0.60799999999999998, closed='right'),
Interval(0.60799999999999998, 0.81200000000000006, closed='right'),
Interval(0.81200000000000006, 2.25, closed='right')], dtype=object)