创建一个熊猫系列的负数箱

时间:2018-10-22 10:41:10

标签: python pandas

我想为减速度值创建一个熊猫系列的负数仓。

df['data_bin'] = pd.cut(df['data'], [0,-0.98,-1.96,-2.94,-3.92,-12.00],
                        labels=['0,-0.98','-0.98,-1.96','-1.96,-2.94',
                                '-2.94,-3.92','-3.92,-12.00'])

我遇到以下错误:

  

ValueError:容器必须单调增加。

2 个答案:

答案 0 :(得分:0)

该错误说明垃圾箱必须增加monotonically。因此,您可以反转输入来满足此条件:

B = [0, -0.98, -1.96, -2.94, -3.92, 12.00]
L = ['0,-0.98', '-0.98,-1.96', '-1.96,-2.94', '-2.94,-3.92', '-3.92,-12.00']

df['data_bin'] = pd.cut(df['data'], bins=B[::-1], labels=L[::-1])

答案 1 :(得分:0)

我相信您需要反转输入:

data = pd.DataFrame({'acceleration':[-11,-1,-2,-4]})

bins = [-12.00,-3.92,-2.94,-1.96,-0.98, 0]
labels = ['-3.92,-12.00', '-2.94,-3.92','-1.96,-2.94','-0.98,-1.96','0,-0.98']

data['decceleration_bin'] = pd.cut(data['acceleration'], bins=bins, labels=labels)
print (data)
   acceleration decceleration_bin
0           -11      -3.92,-12.00
1            -1       -0.98,-1.96
2            -2       -1.96,-2.94
3            -4      -3.92,-12.00

您还可以动态创建标签:

data = pd.DataFrame({'acceleration':[-11,-1,-2,-4]})

bins = [-12.00,-3.92,-2.94,-1.96,-0.98, 0]
labels = [f'{j},{i}' for i, j in zip(bins[:-1], bins[1:])] 
print (labels)
['-3.92,-12.00', '-2.94,-3.92', '-1.96,-2.94', '-0.98,-1.96', '0,-0.98']

data['decceleration_bin'] = pd.cut(data['acceleration'], bins=bins, labels=labels)
print (data)
   acceleration decceleration_bin
0           -11      -3.92,-12.00
1            -1       -0.98,-1.96
2            -2       -1.96,-2.94
3            -4      -3.92,-12.00