2017-10-28 94 views
1

我有一個數據框收入數據與國家,地區和收入。我正在嘗試使用聚合來返回平均值,最小值,最大值和計數。我希望能夠計數所在國家的收入大於100Python數據框條件金額

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

請讓我知道,如果拉姆達的方法來計算一個區域內各國可以擴展到一個區域內的數個國家那裏的收入大於100.或者如果有其他更好的方法來解決這個問題。

很多預先感謝。

回答

1

你可以用和條件與lambda使用自定義功能,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 
+0

謝謝你,你的反應十分讚賞。這是一種享受。 – user1254513

+0

歡迎您!美好的一天! – jezrael