将DataFrame分为N个(几乎)相等的片段

2024-04-26 10:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个数据帧:

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会发生什么。你知道吗


Tags: 数据代码iddfsegmentpd末尾总数
2条回答

这应该起作用:

df['segment'] = np.linspace(1, 6, len(df), False, dtype=int)

它创建一个数组大小在1到5之间的int列表。如果您想从5到1,只需在行尾添加[::-1]。你知道吗

事实上,你比你想象的更接近答案。无论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

相关问题 更多 >