【问题标题】:TypeError: ("sort_values() got multiple values for argument 'axis'", 'occurred at index SUMLEV')TypeError:(“sort_values()为参数'axis'获得了多个值”,'发生在索引SUMLEV')
【发布时间】:2017-01-03 05:45:39
【问题描述】:

为什么是这个代码

cdf = census_df[census_df['SUMLEV'] == 50]
cdf = cdf.apply(lambda x:x.sort_values('CENSUS2010POP', axis=0, ascending=False)).reset_index(drop=True)
cdf = cdf.groupby('STNAME').head(3)
cdf.head(20)

出现以下错误

TypeError: ("sort_values() got multiple values for argument 'axis'", 'occurred at index SUMLEV')

虽然这段代码运行良好

cdf = census_df[census_df['SUMLEV'] == 50]
cdf = cdf.groupby('STNAME')
cdf = cdf.apply(lambda x:x.sort_values('CENSUS2010POP', axis=0, ascending=False)).reset_index(drop=True)
cdf = cdf.groupby('STNAME').head(3)
cdf.head(20)

但是在这里我需要做两次 groupby,第一次是在排序之前,然后是在排序之后选择前 3 个值。我想先排序,然后分组,然后为每个组选择 3 个。

csv文件可以找到here

谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你需要换行:

    cdf = cdf.apply(lambda x:x.sort_values('CENSUS2010POP', axis=0, ascending=False)).reset_index(drop=True)
    

    到:

    cdf = cdf.sort_values('CENSUS2010POP', ascending=False).reset_index(drop=True)
    

    .sort_values() 应用于数据框时,它将按您指定的列对所有列进行排序,在这种情况下为CENSUS2010POP。您不必将排序应用于所有列。

    【讨论】:

    • 实际上我收到错误:AttributeError: Cannot access callable attribute 'sort_values' of 'DataFrameGroupBy' objects,尝试使用'apply'方法
    • 我认为您在排序之前使用的是groupby。您可以直接将sort_values() 应用于原始数据框,无需groupby。稍后对数据框进行分组。从pandas group by is stable开始,数据框会一直排在group by之后。
    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 2019-01-03
    • 2019-07-05
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2014-03-12
    相关资源
    最近更新 更多