You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中计算Rank列字符串的数值差值

Pandas计算Rank列数字差值解决方案

我有如下Pandas DataFrame,其中Rank列的数据类型为字符串:

Race_ID   Date           Student_ID      Rank  
1         1/1/2023       1               100-20     
1         1/1/2023       2               40-10       
2         11/9/2022      3               100-5     
3         17/4/2022      5               100-0     
3         17/4/2022      2               4-0     
4         1/3/2022       1               10-5        

需要提取Rank列中的两个数字并计算它们的差值,最终得到如下结果:

Race_ID   Date           Student_ID      Rank      New_column
1         1/1/2023       1               100-20    80 
1         1/1/2023       2               40-10     30  
2         11/9/2022      3               100-5     95
3         17/4/2022      5               100-0     100
3         17/4/2022      2               4-0       4
4         1/3/2022       1               10-5      5 

方法一:使用str.split拆分后计算

通过str.split将Rank列按-拆分,转换为整数后直接计算差值:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Race_ID': [1,1,2,3,3,4],
    'Date': ['1/1/2023', '1/1/2023', '11/9/2022', '17/4/2022', '17/4/2022', '1/3/2022'],
    'Student_ID': [1,2,3,5,2,1],
    'Rank': ['100-20', '40-10', '100-5', '100-0', '4-0', '10-5']
})

# 拆分并计算差值
df['New_column'] = df['Rank'].str.split('-', expand=True).astype(int).apply(lambda x: x[0] - x[1], axis=1)

print(df)

方法二:使用str.extract提取数字

通过正则表达式提取Rank列中的两个数字,再计算差值,这种方式更直观,适合需要保留中间值的场景:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'Race_ID': [1,1,2,3,3,4],
    'Date': ['1/1/2023', '1/1/2023', '11/9/2022', '17/4/2022', '17/4/2022', '1/3/2022'],
    'Student_ID': [1,2,3,5,2,1],
    'Rank': ['100-20', '40-10', '100-5', '100-0', '4-0', '10-5']
})

# 提取两个数字列
df[['num1', 'num2']] = df['Rank'].str.extract(r'(\d+)-(\d+)').astype(int)
# 计算差值
df['New_column'] = df['num1'] - df['num2']
# 可选:删除中间生成的num1和num2列
df = df.drop(columns=['num1', 'num2'])

print(df)

两种方法都能得到符合预期的结果,可根据实际需求选择。

内容的提问来源于stack exchange,提问作者Ishigami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:33:18