【问题标题】:Sorting the index of this dataset?排序这个数据集的索引?
【发布时间】:2019-11-06 03:26:15
【问题描述】:

我目前正在尝试整理这个数据集:

     A  
1    x
101  y
104  a
11   b
111  z
119  c
13   d
131  w

我已将sort_index() 函数应用于我的数据框,称为X_train

X_train.sort_index()

但是,我希望我的索引按如下方式排序:

     A  
1    x
11   b
13   d
101  y
104  a
111  z
119  c
131  w

pandas 中的任何函数或任何 Pythonic 库都可以做到这一点吗?

【问题讨论】:

  • 看起来熊猫sort_index()需要inplace=True,所以不妨试试X_train.sort_index(inplace=True)
  • 你现在做的事情怎么不起作用? (例如:如果你的索引是数字的,它应该按照你的意愿排序 - 如果它是文本,那么它不会......)
  • 你已经在这样做了。
  • @PeptideWitch 我刚刚尝试使用它,但出现此错误:AttributeError: 'NoneType' object has no attribute 'sort_index'
  • 这意味着您的X_train 定义不正确,因此您需要仔细检查您的数据框是否被定义为 X_train。如果遇到困难,请随时发布更多代码。

标签: python pandas sorting training-data


【解决方案1】:

任一种类型:

X_train = X_train.sort_index()

或:

X_train.sort_index(inplace=True)

【讨论】:

    【解决方案2】:

    实际上你想对你的 DataFrame 进行排序:

    • 首先是键的长度(作为字符串),
    • 然后是它的价值

    为此,您可以使用以下代码:

    df['ind'] = df.index.astype('str')
    df['len'] = df.ind.str.len()
    df = df.sort_values(['len', 'ind']).drop(columns=['len', 'ind'])
    

    另一个更简洁的解决方案是:

    df.iloc[np.argsort(df.index.map(lambda it: (len(str(it)), it)))]
    

    想法是:

    • 为每个索引值计算一个元组“长度,值”(lambda 函数)。
    • 执行 argsort - 你会得到按这些元组排序的行的位置。
    • 从这些位置检索元素。

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 2019-07-21
      • 2021-08-10
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多