pandas '无法访问'DataFrameGroupBy'对象的可调用属性'sort_values',请尝试使用'apply'方法'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51775601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'
提问by Kalsoom Malik
I am trying to sort numbers column in dataframe but getting this error 'id' column has count of id's at specific stations. e.g. 2272, 2202, 1855, etc.
我正在尝试对数据框中的数字列进行排序,但收到此错误“id”列在特定站有 id 的计数。例如 2272、2202、1855 等。
df.sort_values(by=['id'])
However, I am getting this error:
但是,我收到此错误:
'Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method'
'无法访问'DataFrameGroupBy'对象的可调用属性'sort_values',请尝试使用'apply'方法'
回答by Thtu
You're trying to call a DataFrame
method from GroupBy
object. If your goal is to sort within each group, you can simply pass multiple keys in by
:
您正在尝试DataFrame
从GroupBy
对象调用方法。如果您的目标是在每个组内排序,您可以简单地传入多个键by
:
with df
as a dataframeand not a groupby object ...
与df
作为一个数据帧,而不是GROUPBY对象...
df.sort_values(by=['groupby_key1', 'groupby_key2', '...', 'id'])
If you want to sort within the group by, do as the error message suggests and use apply
(with df
as a dataframeand not a groupby object):
如果要在组内排序,请按照错误消息的建议进行操作并使用apply
(df
作为数据框而不是 groupby 对象):
gb = df.groupby(['gropuby_key1', 'groupby_key2', '...'])
gb.apply(lambda _df: _df.sort_values(by=['id'])