简体   繁体   English

如何按排序后的列值将列分为5组,然后添加列的

[英]How to divide a column into 5 groups by the column value sorted, and then add column's

How to divide an column into 5 groups by the column's value sorted. 如何按列的值将列分为5组。

and add a column by the groups 并按组添加一列

for example 例如

import pandas as pd
df = pd.DataFrame({'x1':[1,2,3,4,5,6,7,8,9,10]})

and I want add columns like this: 我想添加像这样的列:

You probably want to look at pd.cut , and set the argument bins to an integer of however many groups you want, and the labels argument to False (to return integer indicators of your groups instead of ranges): 您可能希望查看pd.cut ,并将参数bins设置为想要的pd.cut多个组的整数,并将labels参数设置为False (以返回组的整数指示符,而不是范围):

df['add_col'] = pd.cut(df['x1'], bins=5, labels=False) + 1

>>> df
   x1  add_col
0   1        1
1   2        1
2   3        2
3   4        2
4   5        3
5   6        3
6   7        4
7   8        4
8   9        5
9  10        5

Note that the + 1 is only there so that your groups are numbered 1 to 5 , as in your desired output. 请注意, + 1仅在此处,因此您的组编号为15 ,如所需的输出所示。 If you don't say + 1 they will be numbered 0 to 4 如果您不说+ 1 ,则会将其编号为04

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM