python – 在pandas中按多个条件分组
作者:互联网
我有一个像这样的pandas数据结构:
>>> df
Benny Daniel Doris Eric Jack Zoe
Age 75 30 95 25 28 23
Salary 2000 9000 100000 10000 12000 20000
我想找到几个不同组的平均年龄和工资,其中每个组都是列的子集,它们可能重叠,例如这个字典:
{'Parrot lovers': ['Doris', 'Benny'], 'Tea Drinkers': ['Doris', 'Zoe'],\
'Maintainance': ['Benny', 'Jack'], 'Coffee Drinkers': ['Benny', 'Eric'],\
'Senior Management': ['Doris', 'Zoe', 'Jack']}
如何设计一个可以执行此操作的groupby函数?
解决方法:
以下是我设置问题的方法……
import StringIO
import pandas as pd
df = """index Benny Daniel Doris Eric Jack Zoe
Age 75 30 95 25 28 23
Salary 2000 9000 100000 10000 12000 20000"""
df = pd.read_csv(StringIO.StringIO(df),sep="\s+").set_index('index')
d = {'Parrot lovers': ['Doris', 'Benny'], 'Tea Drinkers': ['Doris', 'Zoe'],\
'Maintainance': ['Benny', 'Jack'], 'Coffee Drinkers': ['Benny', 'Eric'],\
'Senior Management': ['Doris', 'Zoe', 'Jack']}
对于解决方案Just Use .loc并遍历字典…
averages = {k:df.loc[:,v].mean(axis=1) for k,v in d.iteritems()}
print pd.DataFrame(averages).T #gives the nice printout...
index Age Salary
Coffee Drinkers 50.000000 6000
Maintainance 51.500000 7000
Parrot lovers 85.000000 51000
Senior Management 48.666667 44000
Tea Drinkers 59.000000 60000
标签:data-analysis,python,pandas 来源: https://codeday.me/bug/20190830/1768871.html