[PYTHON] Replace column names / values with pandas dataframe

Contents

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.

Advance preparation

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

Rename column

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

Change record value

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

Replace column names / values with pandas dataframe
Rename column names with django-south
Get one column from DataFrame with DataFrame
Bulk Insert Pandas DataFrame with psycopg2
Update Pandas DataFrame elements by column name
[Python / Pandas] A bug occurs when trying to replace a DataFrame with `None` with` replace`
How to replace with Pandas DataFrame, which is useful for data analysis (easy)
Remove rows with duplicate indexes in pandas DataFrame
Handle integer types with missing values in Pandas
Aggregate VIP values of Smash Bros. with Pandas
Find the sum of unique values with pandas crosstab
Check if the expected column exists in Pandas DataFrame
Extract N samples for each group with Pandas DataFrame
How to extract null values and non-null values with pandas
3D plot Pandas DataFrame
Processing datasets with pandas (1)
Convert 202003 to 2020-03 with pandas
Processing datasets with pandas (2)
11. Replace tabs with spaces
Merge datasets with pandas
Learn Pandas with Cheminformatics
Data visualization with pandas
Data manipulation with Pandas!
Python application: Pandas # 3: Dataframe
Replace all flags written with short names in maya.cmds with long names
Check what line caused the error with apply () (dataframe, Pandas)
Calculate the time difference between two columns with Pandas DataFrame
A handy function to add a column anywhere in a Pandas DataFrame
Convert DataFrame column names from Japanese to English using Googletrans