【问题标题】:How to sort dataframe with ignoring prefixes?如何对忽略前缀的数据框进行排序?
【发布时间】:2018-02-21 13:45:08
【问题描述】:

我可以像这样按列对数据框进行排序:

df.sort(columns='sort_index', inplace=True)

我可以对数组进行排序,忽略前缀如下:

array.sort(key=lambda element: re.sub(re, "", element))

但是如何对忽略前缀的数据框进行排序?

【问题讨论】:

  • 可以添加数据样本吗?
  • 使用 re.sub 逻辑将“key”列添加到您的数据框,然后对该“key”进行排序。排序后,drop('key', axis=1)。另外,您需要使用sort_values

标签: python pandas dataframe data-structures


【解决方案1】:

我认为您需要 str.replaceargsort 用于索引,然后通过 iloc 选择哪些重新排序行:

df = pd.DataFrame({
    'B': list(range(9)), 
}, index=['1s','2d','2a','1c','22d','1b','2b','1c','4d'])
print (df)
     B
1s   0
2d   1
2a   2
1c   3
22d  4
1b   5
2b   6
1c   7
4d   8

idx = df.index.str.replace('\D+', '').astype(int).argsort()
df = df.iloc[idx]
print (df)
     B
1s   0
1c   3
1b   5
1c   7
2d   1
2a   2
2b   6
4d   8
22d  4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2014-04-14
    • 1970-01-01
    相关资源
    最近更新 更多