[英]Sorting dataframe by absolute value of a row
I have the following dataframe:我有以下 dataframe:
import pandas as pd
data = {0: [-1, -14], 1: [-3, 2], 2: [7, 10], 4: [-10, 15]}
df = pd.DataFrame(data)
I know how to sort an specific row:我知道如何对特定行进行排序:
df.sort_values(by=0, ascending=False, axis=1)
How is it possible to sort the dataframe by the absolute value of the first row?如何按第一行的绝对值对 dataframe 进行排序? In this case I will have something like:
在这种情况下,我会有类似的东西:
sorted_data = {0: [-10, 15], 1: [7, 10], 2: [-3, 2], 4: [-1, -14]}
sort series by slicing of row 0
and passing its index to indexing the original df
通过对第
0
行进行切片并将其索引传递给索引原始df
对系列进行排序
df_sorted = df[df.iloc[0].abs().sort_values(ascending=False).index]
Out[94]:
4 2 1 0
0 -10 7 -3 -1
1 15 10 2 -14
Let us try argsort
让我们试试
argsort
df = df.iloc[:,(-df.loc[0].abs()).argsort()]
Pandas 1.1 gives a key
argument: Pandas 1.1 给出了一个
key
论点:
df.sort_values(0, axis=1, key=np.abs, ascending=False)
4 2 1 0
0 -10 7 -3 -1
1 15 10 2 -14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.