我有这样一个数据帧:
import pandas as pd
df = pd.DataFrame(
{
'pos': ['A1', 'B03', 'A2', 'B01', 'A3', 'B02'],
'ignore': range(6)
}
)
pos ignore
0 A1 0
1 A03 1
2 A2 2
3 B01 3
4 B3 4
5 B02 5
我想根据pos
进行排序
0
因此,理想的结果是
pos ignore
0 A1 0
1 B01 3
2 A2 2
3 B02 5
4 A03 1
5 B3 4
我现在是这样做的:
df[['let', 'num']] = df['pos'].str.extract(
'([A-Za-z]+)([0-9]+)'
)
df['num'] = df['num'].astype(int)
df = (
df.sort_values(['num', 'let'])
.drop(['let', 'num'], axis=1)
.reset_index(drop=True)
)
这是可行的,但我不喜欢的是,我需要两个临时列,以后必须再次删除。有没有更直接的方法
您可以将
argsort
与zfill
一起使用,并对数字进行第一次排序,如01, 02, 03
等。这样您就不必分配/删除列:这里有一个方法:
输出
相关问题 更多 >
编程相关推荐