pandas groupby 和 agg 出现 TypeError
pandas groupby and agg getting TypeError
我看到可以执行 groupby 然后 agg 让 pandas 生成一个新数据帧,该数据帧按您指定的字段对旧数据帧进行分组,然后在某些函数上聚合您指定的字段(在下面的例子中求和)。
然而,当我写下以下内容时:
# initialize list of lists
data = [['tom', 10, 100], ['tom', 15, 200], ['nick', 15, 150], ['juli', 14, 140]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age', 'salary'])
# trying to groupby and agg
grouping_vars = ['Name']
nlg_study_grouped = df(grouping_vars,axis = 0).agg({'Name': sum}).reset_index()
Name
Age
salary
tom
10
100
tom
15
200
nick
15
150
juli
14
140
我希望输出看起来像这样(因为它按 Name
分组,然后对字段 salary
:
求和
Name
salary
tom
300
nick
150
juli
140
该代码在其他人的示例中有效,但我的玩具示例产生了此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-6fb9c0ade242> in <module>
1 grouping_vars = ['Name']
2
----> 3 nlg_study_grouped = df(grouping_vars,axis = 0).agg({'Name': sum}).reset_index()
TypeError: 'DataFrame' object is not callable
我想知道我是不是漏掉了什么蠢东西。
你可以试试这个
print(df.groupby('Name').sum()['salary'])
使用多项功能
print(df.groupby(['Name'])['salary']
.agg([('average','mean'),('total','sum'),('product','prod')])
.reset_index())
如果你想按多列分组,那么你可以尝试在groupby列表中添加多个列名
Ex: df.groupby(['Name','AnotherColumn'])...
另外,你可以参考这个问题
我看到可以执行 groupby 然后 agg 让 pandas 生成一个新数据帧,该数据帧按您指定的字段对旧数据帧进行分组,然后在某些函数上聚合您指定的字段(在下面的例子中求和)。
然而,当我写下以下内容时:
# initialize list of lists
data = [['tom', 10, 100], ['tom', 15, 200], ['nick', 15, 150], ['juli', 14, 140]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age', 'salary'])
# trying to groupby and agg
grouping_vars = ['Name']
nlg_study_grouped = df(grouping_vars,axis = 0).agg({'Name': sum}).reset_index()
Name | Age | salary |
---|---|---|
tom | 10 | 100 |
tom | 15 | 200 |
nick | 15 | 150 |
juli | 14 | 140 |
我希望输出看起来像这样(因为它按 Name
分组,然后对字段 salary
:
Name | salary |
---|---|
tom | 300 |
nick | 150 |
juli | 140 |
该代码在其他人的示例中有效,但我的玩具示例产生了此错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-6fb9c0ade242> in <module>
1 grouping_vars = ['Name']
2
----> 3 nlg_study_grouped = df(grouping_vars,axis = 0).agg({'Name': sum}).reset_index()
TypeError: 'DataFrame' object is not callable
我想知道我是不是漏掉了什么蠢东西。
你可以试试这个
print(df.groupby('Name').sum()['salary'])
使用多项功能
print(df.groupby(['Name'])['salary']
.agg([('average','mean'),('total','sum'),('product','prod')])
.reset_index())
如果你想按多列分组,那么你可以尝试在groupby列表中添加多个列名
Ex: df.groupby(['Name','AnotherColumn'])...
另外,你可以参考这个问题