Python 将数据帧分成N个(几乎)相等的段
假设我有一个如下所示的数据帧:Python 将数据帧分成N个(几乎)相等的段,python,pandas,dataframe,Python,Pandas,Dataframe,假设我有一个如下所示的数据帧: Id ColA 1 2 2 2 3 3 4 5 5 10 6 12 7 18 8 20 9 25 10 26 我希望我的代码在数据帧的末尾创建一个新列,将obvservations的总数除以5,从5到1不等 Id ColA Segment 1 2
Id ColA
1 2
2 2
3 3
4 5
5 10
6 12
7 18
8 20
9 25
10 26
我希望我的代码在数据帧的末尾创建一个新列,将obvservations的总数除以5,从5到1不等
Id ColA Segment
1 2 5
2 2 5
3 3 4
4 5 4
5 10 3
6 12 3
7 18 2
8 20 2
9 25 1
10 26 1
我尝试了以下代码,但不起作用:
df['segment'] = pd.qcut(df['Id'],5)
我还想知道如果我的观察总数不能除以5会发生什么。事实上,你比你想象的更接近答案。无论
len(df)
是否为5的倍数,这都将起作用
bins = 5
df['Segment'] = bins - pd.qcut(df['Id'], bins).cat.codes
df
Id ColA Segment
0 1 2 5
1 2 2 5
2 3 3 4
3 4 5 4
4 5 10 3
5 6 12 3
6 7 18 2
7 8 20 2
8 9 25 1
9 10 26 1
在哪里,
pd.qcut(df['Id'], bins).cat.codes
0 0
1 0
2 1
3 2
4 3
5 4
6 4
dtype: int8
将pd.qcut
返回的分类间隔表示为整数值
另一个示例,对于具有7行的数据帧
df = df.head(7).copy()
df['Segment'] = bins - pd.qcut(df['Id'], bins).cat.codes
df
Id ColA Segment
0 1 2 5
1 2 2 5
2 3 3 4
3 4 5 3
4 5 10 2
5 6 12 1
6 7 18 1
这应该起作用:
df['segment'] = np.linspace(1, 6, len(df), False, dtype=int)
它创建一个数组大小1到5之间的int列表。如果要从5到1,只需在行的末尾添加
[::-1]
。什么是“.cat”、“.code”和“Bins-”代表?@RogerSteinbergpd.qcut
返回一个区间的分类列。这些类别在内部由0-4的整数代码表示(对于5个箱子)。我利用了这一点,并从5中减去,以获得您的预期输出?是否划分为五分位数?@RogerSteinberg不确定什么是五分位数(或它是做什么的),但这会将数据划分为N个分位数(五分位数?),然后标记它们。