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

如何编写Pandas函数处理含k后缀的列值并转为浮点型?

处理带"k"后缀的Pandas列转换为数值型

针对你提到的需求,这里提供两种处理方式,分别对应字面需求和实际业务场景(因为带"k"的数值通常代表千位量级,比如3.3k实际指3300):

一、按字面需求:移除"k"后直接转float

这种方式会把3.3k转为3.3,849转为849.0:

  1. 定义转换函数:
def convert_k_to_float(value):
    str_val = str(value).strip()
    if str_val.endswith('k'):
        return float(str_val[:-1])
    return float(str_val)
  1. 应用到DataFrame列:
df['interviews_float'] = df['interviews'].apply(convert_k_to_float)

二、按实际业务场景:转换为真实数值

如果3.3k代表的是3300,那需要在移除"k"后乘以1000:

方法1:使用apply函数

def convert_k_to_numeric(value):
    str_val = str(value).strip()
    if str_val.endswith('k'):
        return float(str_val[:-1]) * 1000
    return float(str_val)

df['interviews_numeric'] = df['interviews'].apply(convert_k_to_numeric)

方法2:矢量化操作(更高效,适合大数据集)

不用循环,直接用Pandas字符串方法和numpy条件判断:

import numpy as np

df['interviews_numeric'] = np.where(
    df['interviews'].str.endswith('k'),
    df['interviews'].str.replace('k', '', regex=False).astype(float) * 1000,
    df['interviews'].astype(float)
)

或者用更简洁的链式操作:

df['interviews_numeric'] = (
    df['interviews']
    .str.replace('k', '', regex=False)
    .astype(float)
    .mul(df['interviews'].str.contains('k').map({True: 1000, False: 1}))
)

测试你的示例数据,处理后结果会是:

0    3300.0
1    2500.0
2    2100.0
3    1100.0
4     849.0
Name: interviews_numeric, dtype: float64

内容的提问来源于stack exchange,提问作者Luis Hernández

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:26:12