It is an operation to replace the column name and record value of the data frame created by pandas. For column names, use the rename method. Use the replace method for the record value.
The environment used jupyter notebook. First, create a data frame.
python
import pandas as pd
df = pd.DataFrame({"fruits":("Mandarin orange", "Apple","Grape"),"Origin":("Ehime","Aomori","Yamanashi")})
df.head()
fruits | Origin | |
---|---|---|
0 | Mandarin orange | Ehime |
1 | Apple | Aomori |
2 | Grape | Yamanashi |
Pass columns as the argument of the rename method. The same data frame is preserved by setting inplace = True.
df.rename(columns = {"fruits":"Fruits"}, inplace = True)
df.head()
Fruits | Origin | |
---|---|---|
0 | Mandarin orange | Ehime |
1 | Apple | Aomori |
2 | Grape | Yamanashi |
Use the replace method.
df["Fruits"].replace("Mandarin orange", "Orange", inplace = True)
df.head()
Fruits | Origin | |
---|---|---|
0 | Orange | Ehime |
1 | Apple | Aomori |
2 | Grape | Yamanashi |
You can also replace multiple values at once.
df["Origin"].replace({"Ehime":"Ehime", "Aomori":"Aomori", "Yamanashi":"Yamanashi"}, inplace = True)
df.head()
Fruits | Origin | |
---|---|---|
0 | Orange | Ehime |
1 | Apple | Aomori |
2 | Grape | Yamanashi |
Recommended Posts