Home >Backend Development >Python Tutorial >Learn how to simply change column names of a Pandas dataframe
Pandas Tutorial: Easily learn how to modify column names, specific code examples are required
Introduction:
Pandas is a widely used data analysis library in Python, providing A large number of powerful functions, including data import, processing, conversion and analysis. During data processing, column names often need to be modified. This article will introduce in detail how to use the methods in the Pandas library to easily modify the column names of the data frame, and provide specific code examples.
import pandas as pd
data = {'Name': ['Tom', 'John', 'Alice', 'Emma'], 'Age': [25, 30, 28, 35], 'Gender': ['Male', 'Male', 'Female', 'Female']} df = pd.DataFrame(data) print(df)
The output results are as follows:
Name Age Gender 0 Tom 25 Male 1 John 30 Male 2 Alice 28 Female 3 Emma 35 Female
new_columns = {'Name': '姓名', 'Age': '年龄', 'Gender': '性别'} df = df.rename(columns=new_columns) print(df)
The output results are as follows:
姓名 年龄 性别 0 Tom 25 Male 1 John 30 Male 2 Alice 28 Female 3 Emma 35 Female
new_columns = ['姓名', '年龄', '性别'] df.set_axis(new_columns, axis='columns', inplace=True) print(df)
The output result is the same as above:
姓名 年龄 性别 0 Tom 25 Male 1 John 30 Male 2 Alice 28 Female 3 Emma 35 Female
df.columns = ['姓名', '年龄', '性别'] print(df)
The output result is the same as before:
姓名 年龄 性别 0 Tom 25 Male 1 John 30 Male 2 Alice 28 Female 3 Emma 35 Female
Summary:
In this article, we introduced how to use the rename method in the Pandas library , set_axis method and directly modify the columns attribute to modify the column names of the data frame. These methods provide a flexible and concise way to modify column names to facilitate data processing and analysis. I hope this article will help you learn and use the Pandas library.
The above is the detailed content of Learn how to simply change column names of a Pandas dataframe. For more information, please follow other related articles on the PHP Chinese website!