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

Pandas中满足条件时将值替换为带索引编号的字符串

实现DataFrame中state为"no"时value列的格式化替换

需求说明

当DataFrame的state列值为"no"时,将value列替换为F{索引值+1}格式的字符串,其余行保留value列原有值。

输入示例

state value
0         yes     6
1          no    14
2          no    3
3         yes   123
4          no    78

解决方案

可以通过Pandas的loc定位条件行,或者结合numpy.where实现批量替换,两种方法都能高效完成需求:

方法1:使用loc定位替换

import pandas as pd

# 构造输入DataFrame
data = {
    'state': ['yes', 'no', 'no', 'yes', 'no'],
    'value': [6, 14, 3, 123, 78]
}
df = pd.DataFrame(data)

# 替换state为"no"的行的value值
df.loc[df['state'] == 'no', 'value'] = 'F' + (df.index + 1).astype(str)

方法2:使用numpy.where批量替换

import pandas as pd
import numpy as np

# 构造输入DataFrame
data = {
    'state': ['yes', 'no', 'no', 'yes', 'no'],
    'value': [6, 14, 3, 123, 78]
}
df = pd.DataFrame(data)

# 条件替换value列
df['value'] = np.where(df['state'] == 'no', 'F' + (df.index + 1).astype(str), df['value'])

输出结果

state value
0         yes     6
1          no    F2
2          no    F3
3         yes   123
4          no    F5

代码说明

  • df.index + 1:将原从0开始的索引值加1,得到1~5的序列
  • astype(str):将数值型的索引序列转为字符串,方便与前缀F拼接
  • 两种方法都仅对state == 'no'的行进行修改,其余行保留value列原始值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:40:50