如何按同时包含数字和字符串的列对熊猫数据框进行排序?

Mig*_*rez 3 python sorting dataframe pandas

我有一个看起来像这样的数据框

         col0         col1  col2   col4
         1    '1ZE7999'  865545   20    20
         2    'R022428'  865584  297     0
         3    34         865665  296     0 
         4    56         865700  297     0
         5    100        865628  292     5
Run Code Online (Sandbox Code Playgroud)

我想按'col0'对其进行排序,首先是数值,然后是字符串,Excel排序的方式

       col0         col1  col2   col4
  3    34         865665  296     0 
  4    56         865700  297     0
  5    100        865628  292     5
  1    '1ZE7999'  865545   20    20
  2    'R022428'  865584  297     0
Run Code Online (Sandbox Code Playgroud)

我用了

df.sort_values(by='col1', ascending=True)
Run Code Online (Sandbox Code Playgroud)

但这不是这样排序的,它从 0-9 排序,然后是 az

      col0         col1  col2   col4
 1    '1ZE7999'  865545   20    20
 5    100        865628  292     5
 3    34         865665  296     0 
 4    56         865700  297     0
 2    'R022428'  865584  297     0
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 7

pd.to_numeric+ sort_values+ loc-

df.loc[pd.to_numeric(df.col0, errors='coerce').sort_values().index]

        col0    col1  col2  col4
3         34  865665   296     0
4         56  865700   297     0
5        100  865628   292     5
1  '1ZE7999'  865545    20    20
2  'R022428'  865584   297     0
Run Code Online (Sandbox Code Playgroud)

细节

pd.to_numeric强制非整数值NaN-

i = pd.to_numeric(df.col0, errors='coerce')
i

1      NaN
2      NaN
3     34.0
4     56.0
5    100.0
Name: col0, dtype: float64
Run Code Online (Sandbox Code Playgroud)

sort_values 对列进行排序,忽略 NaN。

j = i.sort_values()
j

3     34.0
4     56.0
5    100.0
1      NaN
2      NaN
Name: col0, dtype: float64
Run Code Online (Sandbox Code Playgroud)

观察指数。您需要做的就是使用索引重新索引数据帧。无论是locreindex将做到这一点。

df.loc[j.index]

        col0    col1  col2  col4
3         34  865665   296     0
4         56  865700   297     0
5        100  865628   292     5
1  '1ZE7999'  865545    20    20
2  'R022428'  865584   297     0
Run Code Online (Sandbox Code Playgroud)
df.reindex(index=j.index)

        col0    col1  col2  col4
3         34  865665   296     0
4         56  865700   297     0
5        100  865628   292     5
1  '1ZE7999'  865545    20    20
2  'R022428'  865584   297     0
Run Code Online (Sandbox Code Playgroud)

如果您需要重置索引,这很容易完成。

df.loc[j.index].reset_index(drop=True)

        col0    col1  col2  col4
0         34  865665   296     0
1         56  865700   297     0
2        100  865628   292     5
3  '1ZE7999'  865545    20    20
4  'R022428'  865584   297     0
Run Code Online (Sandbox Code Playgroud)