1. pandas.replace()介绍
pandas.Series.replace 官方文档
- to_replace: 需要替换的值
- value:替换后的值
- inplace: 是否在原数据表上更改,默认 inplace=False
- limit:向前或向后填充的最大尺寸间隙,用于填充缺失值
- regex: 是否模糊查询,用于正则表达式查找,默认 regex=False
- method: 填充方式,用于填充缺失值(The method to use when for replacement, when to_replace is a scalar, list or tuple and value is None.)
- pad: 向前填充
- ffill: 向前填充
- bfill: 向后填充
Example

2. 单值替换
2.1 全局替换
df.replace(1, 10)

2.2 选定条件替换
df['attr_1'].replace('场景.季节.冬天', '冬天', inplace=True)

3. 多值替换
3.1 多个值替换同一个值
df.replace([3, 11, 137], 4)

3.2 多个值替换不同值
- 列表List
df.replace([3, 11, 137, 1], [1, 111, 731, 10])

- 字典映射
# 修改不同列
df.replace({'场景.普通运动.跑步':'跑步', 11:100})

# 修改同一列
df.replace({'attr_1':{'场景.普通运动.跑步':'跑步', '场景.户外休闲.爬山':'爬山'}})

4. 模糊查询替换
df.replace('场景.','', regex=True)
df.replace(regex='场景.', value=' ')

df.replace(regex={'场景.': '', '方案.':''})
df.replace(regex=['场景.', '方案.'], value='')

也可以这样
df['Attr_B'] = df['Attr_B'].str.replace('夹克', '大衣')
df

5. 缺失值替换
5.1 method的用法 (向前/后填充)
Example

- 向前填充(以他的前一行的值填充)
s.replace(np.nan, method='pad')
s.replace(np.nan, method='ffill')

- 向后填充(以他的后一行的值填充)
s.replace(np.nan, method='bfill')

5.2 limit的用法 (限制最大填充间隔)
连着多个空值时,limit为几填充几个
Example

s.replace(np.nan, method='ffill', limit=1)

s.replace(np.nan, method='ffill', limit=2)











