Python Dataframe条件求和

时间:2017-10-28 09:09:30

标签: python pandas pandas-groupby

我有一个包含国家,地区和收入的数据框incomeData。我试图使用聚合来返回mean,min,max和count。我希望能够计算收入大于100的国家。

raw_data = {'Country': ['A', 'B', 'C', 'D', 'E'],
            'Region': ['X', 'X', 'X', 'Y', 'Y'],
            'Income': [100, 200, 300, 100, 200]
           }
incomeData = pd.DataFrame(raw_data, columns = ['Country', 'Region', 'Income'])
regionGroup = incomeData.groupby(['Region'], as_index=False)
groupCount = lambda x: x.count()
#CountHighIncome = ?
aggregations = {
    'Country': {groupCount
    },
    'Income': {'min', 'max', 'mean', 'median' #, CountHighIncome
    }
}
incomeSummary = regionGroup.agg(aggregations)
incomeSummary
   Region  Country Income
lambda> median max mean min CountHighIncome
0 X 3 200 300 200 100 2
1 Y 2 150 200 150 100 1

如果某个地区内的国家/地区的lambda方法可以扩展到计算收入大于100的地区内的国家,请告诉我。或者,如果有其他更好的方法可以解决这个问题。

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

您可以将lambda的自定义函数与sum条件一起使用,True s计为1,同时Country已删除lambda函数,并且仅使用count

CountHighIncome = lambda x: (x > 100).sum()
aggregations = {
    'Country': {'count'
    },
    'Income': {'min', 'max', 'mean', 'median',  CountHighIncome
    }
}
incomeSummary = regionGroup.agg(aggregations)
print (incomeSummary)
  Region Income                           Country
            max  min <lambda> mean median   count
0      X    300  100        2  200    200       3
1      Y    200  100        1  150    150       2