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

如何用Python识别表头含100的列并将超100值替换为NaN?

解决方法:识别表头含"100"的列并替换超100的数值为NaN

步骤分解:

  • 筛选表头包含"100"的目标列
  • 将这些列的字符串类型转换为数值类型(示例数据中为字符串格式的数字,必须转换才能进行数值比较)
  • 对转换后的列,把大于100的数值替换为NaN

完整代码实现:

import pandas as pd
import numpy as np

data = {'first_100':  ['25', '1568200', '5'],
        'second_column': ['first_value', 'second_value', 'third_value'],
        'third_100':['89', '9', '589'],
        'fourth_column':['first_value', 'second_value', 'third_value'],
        }

df = pd.DataFrame(data)

# 筛选表头含"100"的列
target_cols = df.columns[df.columns.str.contains('100')]

# 转换为数值类型,errors='coerce'可将非数值内容转为NaN(增强代码健壮性)
df[target_cols] = df[target_cols].apply(pd.to_numeric, errors='coerce')

# 将大于100的值替换为NaN
df[target_cols] = df[target_cols].mask(df[target_cols] > 100, np.nan)

print(df)

输出结果:

first_100 second_column  third_100 fourth_column
0       25.0    first_value       89.0    first_value
1        NaN   second_value        9.0   second_value
2        5.0    third_value        NaN    third_value

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:01:26