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)

以上,问题解决~

相关文章
|
编解码 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
848 0
|
Python
【Python】已解决:(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)
【Python】已解决:(pandas读取DataFrame列报错)raise KeyError(key) from err KeyError: (‘name‘, ‘age‘)
1573 0
|
开发者 Python
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
769 0
|
API 索引 Python
【Pandas】已完美解决:AttributeError: ‘DataFrame‘ object has no attribute ‘ix‘
【Pandas】已完美解决:AttributeError: ‘DataFrame‘ object has no attribute ‘ix‘
752 0
|
Python
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序
【5月更文挑战第2天】使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序。示例代码展示了如何按'Name'和'Age'列排序 DataFrame。先按'Name'排序,再按'Age'排序。sort_values()的by参数接受列名列表,ascending参数控制排序顺序(默认升序),inplace参数决定是否直接修改原DataFrame。
1211 1
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读excel类型文件报错: xlrd.biffh.XLRDError: Excel xlsx file; not supported
pandas读excel类型文件报错: xlrd.biffh.XLRDError: Excel xlsx file; not supported
Pandas 报错 TypeError: ‘Series‘ objects are mutable, thus they cannot be hashed
Pandas 报错 TypeError: ‘Series‘ objects are mutable, thus they cannot be hashed
|
机器学习/深度学习 数据处理 Python
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
274 1
|
11月前
|
数据采集 存储 数据挖掘
Python数据分析:Pandas库的高效数据处理技巧
【10月更文挑战第27天】在数据分析领域,Python的Pandas库因其强大的数据处理能力而备受青睐。本文介绍了Pandas在数据导入、清洗、转换、聚合、时间序列分析和数据合并等方面的高效技巧,帮助数据分析师快速处理复杂数据集,提高工作效率。
312 0