【问题标题】:Count frequency of a number in a column while equals to text in another column计算一列中数字的频率,而等于另一列中的文本
【发布时间】:2016-06-02 04:23:42
【问题描述】:

这是来自示例 csv

大概是这样的5列

剪贴板:

Year  Course  Modul Q1 Q2
2015 Physics CS1203  4  2 
2015 Physics CS1203  4  3 
2015 Physics CS1203  3  1 
2015 Physics CS1203  4  4 
2015 English IR0001  2  5 
2015 English IR0001  1  2 
2015 English IR0001  3  1 
2015 English IR0001  5  3 
2015 English IR0001  4  3

代码:

df = pd.read_clipboard()

我按模块分组,现在我想计算模块 CS1203 中 4 的数量。我是新手,如果这是一个愚蠢的问题,请提前道歉。非常感谢您的帮助。

谢谢

【问题讨论】:

  • 可以添加图片作为文字回答吗?

标签: python pandas


【解决方案1】:

我觉得你需要boolean indexing:

print (df[(df.module == 'CS1203') & (df.q1 == 4)])
   year   course  module  q1  q2
0  2015  Physics  CS1203   4   2
1  2015  Physics  CS1203   4   3
3  2015  Physics  CS1203   4   4

print (len(df[(df.module == 'CS1203') & (df.q1 == 4)]))
3

如果需要计算所有q 列,请先使用melt

df = pd.melt(df, id_vars=['year','course','module'], value_name='q')
   year   course  module  q1  q2
0  2015  Physics  CS1203   4   2
1  2015  Physics  CS1203   4   3
2  2015  Physics  CS1203   3   1
3  2015  Physics  CS1203   4   4
4  2015  English  IR0001   2   5
5  2015  English  IR0001   1   2
6  2015  English  IR0001   3   1
7  2015  English  IR0001   5   3
8  2015  English  IR0001   4   3

print (df[(df.module == 'CS1203') & (df.q == 4)])
    year   course  module variable  q
0   2015  Physics  CS1203       q1  4
1   2015  Physics  CS1203       q1  4
3   2015  Physics  CS1203       q1  4
12  2015  Physics  CS1203       q2  4

print (len(df[(df.module == 'CS1203') & (df.q == 4)]))
4

【讨论】:

  • 感谢@jezrael 昨天的帮助,您的回复非常有帮助。但是,我遇到了另一个问题,非常感谢您的帮助。上面的 csv 文件 - 我想创建一个函数 - 当我们运行脚本时,它要求我们输入模块代码。如果模块代码等于列表中我们的模块,则总长度为 4 和 5 并除以总*100。当用户输入模块代码时,脚本应返回百分比值。你能帮我吗,我该怎么做?非常感谢您的帮助。
【解决方案2】:

您可以先按模块 (df.module == 'CS1203') 过滤您的 DF,然后过滤仅选择匹配 q\d+ RegEx 的列,仅选择 4s 最后计算总和:

In [74]: (df[df.module == 'CS1203'].filter(regex=r'q\d+') == 4).sum()
Out[74]:
q1    3
q2    1
dtype: int64

【讨论】:

    【解决方案3】:

    也许你可以试试这样的:

    df.groupby(['module','q1'])['module'].agg({'Frequency':'count'})
    

    请参考这个post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多