python - 根据列名分组

标签 python pandas

我尝试根据列名称对列进行分组后对列进行平均。下面生成了一个示例数据帧。所有在 _ 前面具有相同字符串的列名需要一起求平均值。输出将是一个 10x3 列。

from pandas import DataFrame 
import numpy as np
df = DataFrame(np.random.randint(0,100,size=(10, 7)))
df.columns = ['9_0', '9_1', '99_0', '99_1', '99_2',  '999_0', '999_1']
df

最佳答案

您可以使用 lambda 函数提取公共(public)字符串,并将其用作按列对数据进行分组的键。

df.groupby(lambda x: x.split('_')[0], axis=1).mean()
Out[903]: 
      9         99   999
0  52.0  50.333333  68.5
1  43.0  44.666667  47.0
2  20.0  62.666667  48.0
3  58.5  65.000000  77.5
4  46.0  64.000000  30.0
5  16.5  55.000000  57.5
6  51.5  48.333333  43.0
7  20.0  44.000000  35.5
8  57.5  11.666667  36.0
9  31.5  28.000000  49.0

关于python - 根据列名分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000361/

相关文章:

python - 如何使用 cassandra-driver for python 将 map 类型插入 cassandra

python - 将每个数字数组元素绘制为一条水平线

python - 通过 ENTRYPOINT 在 Docker 中采购 .bashrc

python - cumsum 限制在一个范围内(python,pandas)

python - 在 python 数据框中查找正则表达式

python - 使用 Pandas 将新行添加到数据框子集中

python setup.py test 使用 pytest 时无法精细测试

python - 我如何使用散列和 pickle 来保存/加载对象

python - Pandas 交叉表 : Change Order of Columns That Are Named as Formatted Dates (mmm yy)

python - Pandas 数据帧: Getting tuples groups separated by 'NaN' in a column