Python 熊猫将组分为第一个值和最后一个值
我有多个数据帧,其结构从10开始,然后从0到10:Python 熊猫将组分为第一个值和最后一个值,python,pandas,Python,Pandas,我有多个数据帧,其结构从10开始,然后从0到10: Type Value 10 0.7666 10 0.6566 10 0.7666 0 0.7666 0 0.5446 1 0.7866 2 0.7695 2 0.1642 3 0.1646 ..... 9 0.1476 9 0.4224 10 0.5446 10 0.6566 到目前为止,我一直在使用以下代码按类型对数据帧进行分组: grouped = df.group
Type Value
10 0.7666
10 0.6566
10 0.7666
0 0.7666
0 0.5446
1 0.7866
2 0.7695
2 0.1642
3 0.1646
.....
9 0.1476
9 0.4224
10 0.5446
10 0.6566
到目前为止,我一直在使用以下代码按类型对数据帧进行分组:
grouped = df.groupby(['Type'])
result = grouped.get_group(10)
它适用于类型0-9,但我也希望将类型10分为两组,以区分第一个值和最后一个值,而不是将其全部放在一个数据帧中,如下图所示:
Type Value
10 0.7666
10 0.6566
10 0.7666
10 0.5446
10 0.6566
为连续组创建组,然后选择使用元组:
g = df['Type'].ne(df['Type'].shift()).cumsum()
g = g.groupby(df['Type']).rank('dense')
grouped = df.groupby(['Type', g])
result = grouped.get_group((10, 1))
print (result)
Type Value
0 10 0.7666
1 10 0.6566
2 10 0.7666
result = grouped.get_group((10, 2))
print (result)
Type Value
11 10 0.5446
12 10 0.6566
为连续组创建组,然后选择使用元组:
g = df['Type'].ne(df['Type'].shift()).cumsum()
g = g.groupby(df['Type']).rank('dense')
grouped = df.groupby(['Type', g])
result = grouped.get_group((10, 1))
print (result)
Type Value
0 10 0.7666
1 10 0.6566
2 10 0.7666
result = grouped.get_group((10, 2))
print (result)
Type Value
11 10 0.5446
12 10 0.6566