python - 字符索引系列 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
解决方案
我们可以用 做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
推荐阅读
- javascript - Discord bot 不播放有年龄限制的视频
- c++ - 段错误在gtest中的堆栈上初始化引用变量
- r - 在 R 中使用 ifelse 语句创建新变量
- r - 使用 data.table 解决方案根据 id 将观察结果分组到指定数量的组中
- javascript - 动画 Javascript OnMouseOver
- python - 使用 for 循环遍历文本文件中的单个单词
- godot - 如何更改脚本中的精灵?
- windows - PWA for Windows 的功能是什么?
- php - 使用 php 我需要有 2 个不同的数据库连接
- d - 模块“testavg”在文件“testavg.d”中,无法读取