python - 将一列与包含分类值的多列进行比较,无需循环

标签 python pandas numpy

我正在尝试将 numpy 数据集上的某些列与包含分类数据的另一组列进行比较:

    Gender | Grade | Score 1 | Score 2 | Score 3
    M      | A     | 12      | 8       | 0
    M      | A     | 8       | 11      | 4
    M      | B     | 10      | 8       | 9
    F      | B     | 12      | 2       | 2
    F      | B     | 11      | 8       | 1
    F      | B     | 1       | 4       | 2

我需要做的是将每个分数列与性别和年级进行比较。然后计算每个类别的平均分。例如,分数 1 中性别为 M、性别为 F 的平均值、A 级平均值和 B 级平均值的平均值。我无法在代码中明确定义类别(或性别和成绩列名称)作为我的实际值数据集具有可变的分类值分布,一些附加列包含分类数据。我可以使用 np.unique() 计算所有分类值,它给出了完整列表。然而,我对如何使用 ufunc、广播、掩码等创建一个矩阵感到困惑,这将允许我将这些列中的每一列与没有循环的分类值进行比较。

理想情况下,输出应该是一个矩阵,其中包含一列中可用的所有类别以及其他列的相关平均值。

            A           B           M           F
Score1      mean(S1,A)  mean(S1,B)  mean(S1, M) mean(S1, F)
Score2      mean(S2,A)  etc         etc         etc
Score3      mean(S3,A)  etc         etc         etc

最佳答案

旋转和连接即

one = df.pivot_table(columns=['Gender'],aggfunc='mean')
two = df.pivot_table(columns=['Grade'],aggfunc='mean')
main  = pd.concat([one,two],1)

                  F            M         A        B     
Score 1     8.000000    10.000000     10.0      8.5
Score 2     4.666667     9.000000      9.5      5.5
Score 3     1.666667     4.333333      2.0      3.5

如果您想要单行解决方案,那么:

main = pd.concat([df.pivot_table(columns=i) for i in ['Grade','Gender']],1) # By default `aggfunc` is mean

如果您只想将分数作为索引,其余作为列:

cols = df.columns[~df.columns.str.contains('Score')]
# Index(['Gender', 'Grade'], dtype='object')
ndf = pd.concat([df.pivot_table(columns=i) for i in cols],1)

关于python - 将一列与包含分类值的多列进行比较,无需循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48061769/

相关文章:

python - 如何进行具有多个过滤器的 Django 数据库查询?

python - Pandas - 多列到 "column name - value"列

python - 在 python pandas 中重新编码数据

python - 为什么Numpy的RGB图像阵列具有4层而不是3层?

python - json.dump 一个 concurrent.futures.Future()?

python - Python中的列表联合算法

python - 如何向 Selenium RC TestSuite 输入参数?

python - 如何根据 pandas 中的出现重新标记 id

python - 'pick_event' 处理程序未拾取 Matplotlib 行

Python 比较两个 3 维 numpy 数组