计算熊猫不均匀的垃圾箱

时间:2017-12-11 01:38:02

标签: python pandas

pd.DataFrame({'email':["a@gmail.com", "b@gmail.com", "c@gmail.com", "d@gmail.com", "e@gmail.com",],
                  'one':[88, 99, 11, 44, 33],
                  'two': [80, 80, 85, 80, 70],
                   'three': [50, 60, 70, 80, 20]})

鉴于此DataFrame,我想为每列计算一,二和三,在特定范围内有多少个值。

范围例如是:0-70,71-80,81-90,91-100

结果将是:

out = pd.DataFrame({'colname': ["one", "two", "three"],
                   'b0to70': [3, 1, 4],
                   'b71to80': [0, 3, 1],
                   'b81to90': [1, 1, 0],
                   'b91to100': [1, 0, 0]})

这会是一个很好的惯用方法吗?

1 个答案:

答案 0 :(得分:7)

这样就可以了:

out = pd.DataFrame()
for name in ['one','two','three']:
    out[name] = pd.cut(df[name], bins=[0,70,80,90,100]).value_counts()
out.sort_index(inplace=True)

返回:

           one  two  three
(0, 70]      3    1      4
(70, 80]     0    3      1
(80, 90]     1    1      0
(90, 100]    1    0      0