[英]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 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.