Pandas groupby count:仅在数字时计数

时间:2017-12-22 22:07:33

标签: python-3.x pandas count pandas-groupby

我有一个带有几个字段的DF。例如:

      Year_end  Week_end Integrado Probs  Duration_hours        Router_name
1225      2017         2        si     1             0.7   C3617_AI670_SARA
1562      2017         2        si   N/A            23.0   CF641_PTC70_SARA
1722      2017         2        si     1           314.1   CH126_R1970_SARA
1731      2017         2        si     1           265.9   CH205_BRR70_SARA
1760      2017         2        si   512             1.5   CO068_ARI70_SARA
1936      2017         2        si    32            23.4   CO721_LE370_SARA
2011      2017         2        si   N/A             0.5   CR015_EMP70_SARA
2335      2017         2        si     1           340.3   RJ046_LR170_SARM
2337      2017         2        si   N/A             2.5   RJ077_LR370_SARM
2342      2017         2        si   N/A             2.0   RJ092_RJA70_SARA
2346      2017         2        si     1           338.3   RJ204_LR670_SARM
2350      2017         2        si   N/A             2.7   RJ210_RJC70_SARA

我正在组织如下:

fieldsX = ['Year_end','Week_end']
f = { 'Router_name':['count'], 'Probs':['count'], 'Duration_hours':['mean'] }
a = a.groupby(fieldsX).agg(f)

这很好用。唯一的问题是字段Probs包含数字和特定字符串N/A。我只想计算所有数字但不 N/A次出现。

所以,count(Router_name) = 12但是count(Probs) **should** be 7。而是我的count(Probs) = 12

我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:2)

以下是您的问题示例:

import pandas as pd

data = dict(letters = list('abc'), numbers=[1,2,'N/A'])

df = pd.DataFrame(data)

# Before
print(df.groupby('letters').count())

# Fix it by converting column to numeric
df.numbers = pd.to_numeric(df.numbers, errors='coerce')

# After
print(df.groupby('letters').count())

将打印:

         numbers
letters         
a              1
b              1
c              1
         numbers
letters         
a              1
b              1
c              0

然而,看到你有'N / A'首先......看看https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas-read-csv,特别是param:na_values。如果这是您阅读的方式,那么最初应该清理数据。如果这是您获取数据帧的方式。