【问题标题】:How to sort values in DataFrame for both numerical and string values?如何在 DataFrame 中对数值和字符串值进行排序?
【发布时间】:2019-12-03 20:35:58
【问题描述】:

我有以下具有混合数据类型的 pandas DataFrame:字符串和整数值。我想使用多个列按降序对该 DataFrame 的值进行排序:PriceName。字符串值(即Name)应该按字母顺序排序,或者实际上可以完全忽略,因为最重要的是数值。

问题是目标列的列表可以同时包含字符串和整数列,例如target_columns = ["Price","Name"]

d = {'1': ['25', 'AAA', 2], '2': ['30', 'BBB', 3], '3': ['5', 'CCC', 2], \
     '4': ['300', 'DDD', 2], '5': ['30', 'DDD', 3],  '6': ['100', 'AAA', 3]}

columns=['Price', 'Name', 'Class']

target_columns = ['Price', 'Name']
order_per_cols = [False] * len(target_columns)

df = pd.DataFrame.from_dict(data=d, orient='index')
df.columns = columns
df.sort_values(list(target_columns), ascending=order_per_cols, inplace=True)

目前,此代码失败并显示以下消息:

TypeError: '

预期输出:

Price    Name    Class
300      DDD     2
100      AAA     3
30       DDD     3
30       BBB     3
25       AAA     2
5        CCC     2

【问题讨论】:

  • 你的预期输出是什么?
  • @Erfan:请看我的更新。但正如我所说,如果在target_columns中有某种方法可以识别字符串列的排序,则可以忽略它们。
  • 那为什么不直接df = df.sort_values('Price', ascending=False)呢?

标签: python pandas


【解决方案1】:

如果我对您的理解正确,您需要一种通用方式,将 object 列从您的选择中排除。

我们可以为此使用DataFrame.select_dtypes,然后对数字列进行排序:

# df['Price'] = pd.to_numeric(df['Price'])
numeric = df[target_columns].select_dtypes('number').columns.tolist()
df = df.sort_values(numeric, ascending=[False]*len(numeric))
   Price Name  Class
4    300  DDD      2
6    100  AAA      3
2     30  BBB      3
5     30  DDD      3
1     25  AAA      2
3      5  CCC      2

【讨论】:

  • numeric 是否允许 int64float
  • 是的,引用自文档:"要选择所有数字类型,请使用 np.number 或 'number'"
  • 抱歉,在我的情况下,所有列都可能是“对象”。那些确实是数字的也可能是对象或日期时间,正如您在 Price 的情况下看到的那样。
  • 哦,还没有看到你的行df['Price'] = pd.to_numeric(df['Price'])。但是我怎么知道Price应该被转换成numeric呢?我事先没有任何关于列类型的信息。
  • AttributeError: 'Series' 对象没有属性 'select_dtypes'
【解决方案2】:

另一种解决方案可能是 -

在 sort_values 函数中使用 'by' 参数

d = ({'1': ['25', 'AAA', 2], '2': ['30', 'BBB', 3], '3': ['5', 'CCC', 2], \
     '4': ['300', 'DDD', 2], '5': ['30', 'DDD', 3],  '6': ['100', 'AAA', 3]})

df = pd.DataFrame.from_dict(data=d,columns=['Price','Name','Class'],orient='index')
df['Price'] = pd.to_numeric(df['Price'])
df.sort_values(**by** = ['Price','Name'],ascending=False)

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2019-05-08
    • 2017-04-17
    • 1970-01-01
    • 2011-10-09
    • 2014-10-28
    相关资源
    最近更新 更多