pandas replace
时间: 2023-10-15 10:05:59 浏览: 58
In pandas, the `replace()` method is used to replace values in a DataFrame or Series.
Syntax:
```python
DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad')
```
Parameters:
- `to_replace`: Value to be replaced.
- `value`: Value to be replaced with.
- `inplace`: Whether to modify the DataFrame in place or return a new DataFrame.
- `limit`: Maximum number of replacements to make.
- `regex`: Whether to interpret `to_replace` as a regular expression.
- `method`: Method to use when replacing values. Default is 'pad', which replaces with the previous value.
Example:
```python
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['John', 'Sam', 'Emily', 'Jane', 'Tom'],
'Age': [25, 30, 21, 28, 35],
'Gender': ['M', 'M', 'F', 'F', 'M'],
'Salary': [50000, 60000, 45000, 55000, 70000]}
df = pd.DataFrame(data)
# Replace all occurrences of 'M' with 'Male'
df.replace(to_replace='M', value='Male', inplace=True)
print(df)
```
Output:
```
Name Age Gender Salary
0 John 25 Male 50000
1 Sam 30 Male 60000
2 Emily 21 F 45000
3 Jane 28 F 55000
4 Tom 35 Male 70000
```
阅读全文