python - 如何按行值过滤和分组条目

标签 python pandas

我有以下数据框:

df = 
ID   GROUP_1  GROUP_2  GROUP_3  GRADE
1A   AAA      BBB      AAA      5
1B   BBB      BBB      CCC      4
1C   AAA      BBB      BBB      4

我想计算成绩的行数 5 , 4 , .., 1对于 GROUP 的每个唯一值。请注意,在第 1 行中,AAA 出现了 2 次。 ,不过我数了一次。

给定数据集的预期输出如下:

GROUP  GRADE_1   GRADE_2   GRADE_3   GRADE_4   GRADE_5
AAA    0         0         0         1         1
BBB    0         0         0         2         1
CCC    0         0         0         1         0

我有下面给出的代码,它工作正常,不包括分组( groupby('GRADE') )。我不知道如何按 GRADE 对结果进行分组并创建列GRADE_1 , GRADE_2 ,..., GRADE_5 .

df.groupby('GRADE').filter(regex="^GROUP").stack().reset_index(level=1, drop=True).reset_index().drop_duplicates()[0].value_counts()

最佳答案

试试这个:

In [56]: df
Out[56]:
   ID GROUP_1 GROUP_2 GROUP_3  GRADE
0  1A     AAA     BBB     AAA      5
1  1B     BBB     BBB     CCC      4
2  1C     AAA     BBB     BBB      4

In [57]: (df.set_index('GRADE')
    ...:    .filter(like='GROUP_')
    ...:    .stack()
    ...:    .to_frame('GROUP')
    ...:    .reset_index()
    ...:    .pivot_table(index='GROUP', columns='GRADE', aggfunc='size', fill_value=0)
    ...: )
    ...:
Out[57]:
GRADE  4  5
GROUP
AAA    1  2
BBB    4  1
CCC    1  0

关于python - 如何按行值过滤和分组条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351284/

相关文章:

python - 从数据框中提取共现数据

python - 将Kibana查询(创建索引模式)转换为Python请求

python - 获取分类变量的类别列表(Python Pandas)

python - Pandas 从系列扩展到多索引

python - 在 Python 中从矩阵中提取行并将该行用作 Matplotlib 中的颜色

python - 如何使用离散数据对 Pandas 中的数据进行重新采样?

python - 如何使用 Pandas 访问列中的列

python - 使用一个索引将未对齐的时间序列加载到 DataFrame 中?

python - 读取文件并检查数据是否在文件中。 Python

python - 在网格中递归收集硬币