python - 在python中按数字部分按升序对包含数字和字母的字符串列进行排序

标签 python pandas numpy

我的 table 是:

ID       Order_ID   Period
1234      2305333   Monthly
1234      4148915   Annual
1234      3136815   Monthly
1234      5309581   Monthly
9876      W~100040  Annual
9876      W~132759  Annual
9876      W~30094   Annual
9876      W~339658  Annual
9876      W~58943   Annual

我们希望根据 ID 和顺序对其进行排序,以便输出如下所示:

ID      Order_ID    Period
1234    2305333     Monthly
1234    3136815     Monthly
1234    4148915     Annual
1234    5309581     Monthly
9876    W~30094     Annual
9876    W~58943     Annual
9876    W~100040    Annual
9876    W~132759    Annual
9876    W~339658    Annual

我们本质上想要的是能够基于数字对 Order_ID 进行排序,即使我们既有字母也有数字,并且我们希望保留该列原样。

我们尝试使用以下代码: df.loc[pd.to_numeric(df.Order_ID,errors='coerce').sort_values().index]

但没有得到想要的结果。

我们将非常感谢您的帮助。

最佳答案

使用正则表达式提取订单 ID 的数字部分:

result = (
    df.assign(order_no=lambda x: x["Order_ID"].str.extract(".*?(\d+)").astype("int"))
    .sort_values(["ID", "order_no"])
    .drop(columns="order_no")
)

关于python - 在python中按数字部分按升序对包含数字和字母的字符串列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71785741/

相关文章:

python - 按空格将字符串拆分为 N 个元素,保留带引号的子字符串

Python if 语句的结果放入pandas dataframe中

python - Pandas 数据框 - 基于组的每列的总和

python - 在Python中导入颜色科学模块时出现"TypeError"

Python : save dictionaries through numpy. 保存

python - 使用步幅填充 numpy 滚动窗口操作

python - 写入不带任何小数位的 float

python - `type` 的第一个参数有什么作用?

python - ValueError : Mime type rendering requires nbformat>=4. 2.0 但未安装

Python:打开大型文本文件,但仅加载包含预定义列值的行