Pandas报错AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects

简介: Pandas报错AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects

Pandas报错AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects


完整报错如下:

AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects, try using the 'apply' method

报错代码如下:

import pandas as pd
data = pf.read_csv('test.csv',header = 0)
df = pd.DataFrame(data)
df = df.groupby('date', group_keys=False).sort_values('Value', ascending=False).groupby('date').head(10).reset_index()
print(df)

报错原因:

groupby 之后变成了 DataFrameGroupBy,不能直接调用 sort_values() 函数,需使用 apply() 函数,代码更改为如下:

import pandas as pd
data = pf.read_csv('test.csv',header = 0)
df = pd.DataFrame(data)
df = df.groupby('date', group_keys=False).apply(lambda x: x.sort_values('virus_connectivity', ascending=False)).groupby('date').head(10).reset_index()
print(df)

以上,问题解决~

相关文章
|
8天前
|
Python
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序。示例代码展示了如何按'Name'和'Age'列排序 DataFrame。先按'Name'排序,再按'Age'排序。sort_values()的by参数接受列名列表,ascending参数控制排序顺序(默认升序),inplace参数决定是否直接修改原DataFrame。
21 1
|
7月前
|
编解码 Python
pandas - read_csv报错:‘utf-8‘/‘gbk‘ codec can‘t decode byte 0xb1 in position 0:invalid start byte
pandas - read_csv报错:‘utf-8‘/‘gbk‘ codec can‘t decode byte 0xb1 in position 0:invalid start byte
145 0
pandas读excel类型文件报错: xlrd.biffh.XLRDError: Excel xlsx file; not supported
pandas读excel类型文件报错: xlrd.biffh.XLRDError: Excel xlsx file; not supported
Pandas pd.merge() 报错:ValueError: You are trying to merge on int64 and object columns.
Pandas pd.merge() 报错:ValueError: You are trying to merge on int64 and object columns.
Pandas pd.merge() 报错:ValueError: You are trying to merge on int64 and object columns.
Pandas 报错 TypeError: ‘Series‘ objects are mutable, thus they cannot be hashed
Pandas 报错 TypeError: ‘Series‘ objects are mutable, thus they cannot be hashed
|
Python
Pandas报错no attribute 'convert_dtypes'解决办法
Pandas报错no attribute 'convert_dtypes'解决办法
232 0
|
Python
pandas中报错:TypeError: reduction operation ‘argmax‘ not allowed for this dtype 的解决办法
pandas中报错:TypeError: reduction operation ‘argmax‘ not allowed for this dtype 的解决办法
728 0
pandas中报错:TypeError: reduction operation ‘argmax‘ not allowed for this dtype 的解决办法
|
Python
报错:import pandas._libs.parsers as parsers RuntimeWarning
报错:import pandas._libs.parsers as parsers RuntimeWarning
|
17天前
|
数据挖掘 数据处理 索引
python常用pandas函数nlargest / nsmallest及其手动实现
python常用pandas函数nlargest / nsmallest及其手动实现
35 0
|
17天前
|
Python
如何使用Python的Pandas库进行数据透视图(melt/cast)操作?
Pandas的`melt()`和`pivot()`函数用于数据透视。基本步骤:导入pandas,创建DataFrame,然后使用这两个函数变换数据。示例代码:导入pandas,定义一个包含'Name'和'Age'列的DataFrame,使用`melt()`转为长格式,再用`pivot()`恢复为宽格式。
26 1