简体   繁体   English

重新排序行数据

[英]Re-order row data

Based on this question Can't Re-Order Columns Data , how to do it for the dataframe row? 基于这个问题, 无法对列数据重新排序 ,如何对dataframe行进行dataframe because I have a problem, not in the column order but the row order. 因为我有问题,不是列顺序而是行顺序。

my data looks like this: 我的数据如下所示:

    B1  B2
B1  1   1
B10 1   1
B11 1   1
B12 1   1
B2  1   1
B20 1   1
B21 1   1
B22 1   1
B3  1   1
B30 1   1
B31 1   1

my expected result: 我的预期结果:

    B1  B2
 B1 1   1
 B2 1   1
 B3 1   1
B10 1   1
B11 1   1
B12 1   1
B20 1   1
B21 1   1
B22 1   1
B30 1   1
B31 1   1

you can use natsort 你可以使用natsort

import natsort as ns
df.reindex(ns.natsorted(df.index))

     B1  B2
B1    1   1
B2    1   1
B3    1   1
B10   1   1
B11   1   1
B12   1   1
B20   1   1
B21   1   1
B22   1   1
B30   1   1
B31   1   1

Or: 要么:

i=df.index.to_series().str.extract('(\d+)',expand=False).astype(float).sort_values().index
df.reindex(i)

You can use parameter key in sorted function and pass output to DataFrame.reindex : 您可以在已排序的函数中使用参数key并将输出传递给DataFrame.reindex

df = df.reindex(sorted(df.index, key=lambda x: float(x[1:])))
print (df)
     B1  B2
B1    1   1
B2    1   1
B3    1   1
B10   1   1
B11   1   1
B12   1   1
B20   1   1
B21   1   1
B22   1   1
B30   1   1
B31   1   1

Alternative is Series.str.extract numeric, convert to floats and get positions of sorted values by Index.argsort , last change order by DataFrame.iloc : 替代方法是Series.str.extract数字,转换为浮点数,然后通过Index.argsort获取排序值的Index.argsort ,最后一次更改顺序通过DataFrame.iloc

df = df.iloc[df.index.str.extract('(\d+)', expand=False).astype(float).argsort()]
print (df)
     B1  B2
B1    1   1
B2    1   1
B3    1   1
B10   1   1
B11   1   1
B12   1   1
B20   1   1
B21   1   1
B22   1   1
B30   1   1
B31   1   1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM