【问题标题】:sort_values() got an unexpected keyword argument 'by'sort_values() 得到了一个意外的关键字参数“by”
【发布时间】:2020-02-17 19:21:34
【问题描述】:
for i in str_list:   #str_list is a set contain some strings 
    df.loc[i].sort_values(by = 'XXX')
**TypeError**: sort_values() got an unexpected keyword argument 'by' ".
>>> type(df.loc[i])
>>> pandas.core.frame.DataFrame

但它可以在 for 循环之外工作!

df.loc['string'].sort_values(by = 'XXX')
>>> type(df.loc['string'])
>>> pandas.core.frame.DataFrame

我很困惑。

【问题讨论】:

  • df.loc[something] 可能会返回一个系列或一个数据帧。如果something在索引中出现多次,则结果是一个DataFrame。

标签: python pandas dataframe


【解决方案1】:

这是因为 loc 运算符的结果在您的情况下是 pandas.Series 对象。在这种情况下,sort_values 没有关键字参数by,因为它只能对系列值进行排序。在pandas.DataFrame 中调用sort values 时,看看签名的区别

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

当您在pandas.Series 中调用sort_values

http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.sort_values.html

【讨论】:

    【解决方案2】:

    要补充答案, 为什么它在一种情况下返回一个系列,而在另一种情况下返回一个数据框?

    .loc 函数在第一种情况下返回一个系列

    for i in str_list: #str_list 是一个包含一些字符串的集合

    df.loc[i].sort_values(by = 'XXX')

    因为参数 i 在 DataFrame 中只出现一次。

    在第二种情况下,“字符串”是重复的,因此将返回一个 DataFrame。

    df.loc['string'].sort_values(by = 'XXX')

    如果“字符串”参数不重复,则 请注意,如果 .loc 中的参数在列表中,也会存在一些差异。 例如。

    df.loc['string'] -> 返回一个系列

    df.loc[['string']] -> 返回一个DataFrame

    也许在第二种情况下,您将 ['string'] 作为参数而不是 'string' ?

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 2021-03-17
      • 2020-10-01
      • 2018-06-19
      相关资源
      最近更新 更多