pandas replace
时间: 2023-10-12 17:09:10 浏览: 60
pandas值替换方法
5星 · 资源好评率100%
The `replace()` method in pandas is used to replace values in a DataFrame or Series object.
Syntax:
```python
DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
```
Parameters:
- `to_replace`: The value to be replaced.
- `value`: The value to replace `to_replace` with.
- `inplace`: If `True`, the original DataFrame or Series object will be modified. If `False`, a new object will be returned with the replacements made.
- `limit`: The maximum number of replacements to make. If `None`, all occurrences will be replaced.
- `regex`: If `True`, `to_replace` is treated as a regular expression.
- `method`: If `regex` is `True`, this parameter specifies the method to use to replace the values.
Example:
```python
import pandas as pd
data = {'Name': ['John', 'Doe', 'Jane', 'Doe'],
'Age': [25, 30, 35, 40],
'Gender': ['M', 'M', 'F', 'F']}
df = pd.DataFrame(data)
# Replace 'Doe' with 'Smith'
df.replace(to_replace='Doe', value='Smith', inplace=True)
print(df)
```
Output:
```
Name Age Gender
0 John 25 M
1 Smith 30 M
2 Jane 35 F
3 Smith 40 F
```
阅读全文