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

如何用Python从DataFrame混合字符列提取字母并处理纯数字行

解决方法

你可以用Pandas的字符串处理方法实现需求,以下是几种简洁的方案:

方案1:使用str.extract(最直接)

利用正则表达式提取所有字母字符,匹配不到时自动返回NaN,完美贴合需求:

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({
    'char': ['123', 'test', 'te123', 'test123'],
    'count': [24, 25, 26, 26]
})

# 提取字母,纯数字行自动转为NaN
df['char'] = df['char'].str.extract(r'([A-Za-z]+)', expand=False)

print(df)

输出结果:

char  count
0    NaN     24
1   test     25
2     te     26
3   test     26

方案2:使用str.replace结合replace

先移除所有数字字符,再将空字符串替换为NaN:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'char': ['123', 'test', 'te123', 'test123'],
    'count': [24, 25, 26, 26]
})

# 移除所有数字
df['char'] = df['char'].str.replace(r'\d', '', regex=True)
# 空字符串转NaN
df['char'] = df['char'].replace('', np.nan)

print(df)

方案3:自定义逻辑(逐字符判断)

通过apply遍历每个字符串,筛选出字母字符,空结果转NaN:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'char': ['123', 'test', 'te123', 'test123'],
    'count': [24, 25, 26, 26]
})

df['char'] = df['char'].apply(lambda x: ''.join([c for c in x if c.isalpha()]))
df['char'] = df['char'].replace('', np.nan)

print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:12:31