首页 > 解决方案 > 字符索引系列 groupby 非空格

问题描述

我有一个如下所示的系列。理想情况下,我想执行一个 groupby 操作,以找到系列中每个“单词”的平均值(基本上是由空格分隔的索引的每个连续字符串)。

b    0.240322
u    0.279720
f    0.329494
f    0.359549
a    0.371886
l    0.378648
o    0.379713
     0.352408
b    0.350311
i    0.322337
l    0.290646
l    0.265696
s    0.249698
     0.224883
r    0.228836
a    0.239643
n    0.247804
c    0.243472
h    0.257716

这将被翻译为:

buffalo  0.334
bills    0.296
ranch    0.243

标签: pythonpandaspandas-groupby

解决方案


我们可以用 做index一个列reset_index,根据有空格字符的位置创建组,并groupby aggregation用来连接单词并取平均值,然后index用恢复set_index

# Make Index a Column
df = df.reset_index()
# Boolean Index on where spaces are
m = df['index'].eq(' ')
# Groupby Aggregate
df = (
    df.groupby(
        # Groups of words separated by space (excluding the spaces)
        m.cumsum().mask(m),
        as_index=False
    ).agg({
        'index': ''.join,  # Make Words
        'num': 'mean'  # Take Average
    }).set_index('index').rename_axis(None)  # Make index column the index
)

df

              num
buffalo  0.583445
bills    0.349003
ranch    0.498625

使用的示例数据框:

import numpy as np
import pandas as pd

idx = 'buffalo bills ranch'
np.random.seed(5)
df = pd.DataFrame({'num': np.random.random(len(idx))}, index=list(idx))

df

        num
b  0.221993
u  0.870732
f  0.206719
f  0.918611
a  0.488411
l  0.611744
o  0.765908
   0.518418
b  0.296801
i  0.187721
l  0.080741
l  0.738440
s  0.441309
   0.158310
r  0.879937
a  0.274086
n  0.414235
c  0.296080
h  0.628788

推荐阅读