Python|熊猫 dataframe.rename_axis()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
dataframe.rename_axis()
用于重命名 dataframe 中索引或列的轴。
Syntax: DataFrame.rename_axis(mapper, axis=0, copy=True, inplace=False)
Parameters:
mapper : [scalar, list-like, optional] Value to set the axis name attribute.
axis : int or string, default 0
copy : [iboolean, default True] Also copy underlying data
inplace :boolean, default False
Returns: renamed : type of caller or None if inplace=True
有关代码中使用的 CSV 文件的链接,请单击此处
示例 #1:在 nba.csv 文件中将球队“波士顿凯尔特人队”替换为“欧米茄勇士队”
# importing pandas as pd
import pandas as pd
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
# Printing the first 10 rows of the
# dataframe for visualization
df[:10]
输出:
我们将更改行索引并将值增加两倍。
# this will Increase the row index value by twice
df.rename_axis(lambda x:x * 2, axis ="index")
输出:
示例 #2:更改列名
# importing pandas as pd
import pandas as pd
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
# this will add '_X' at the end of each column name
df.rename_axis(lambda x:x+"_X", axis ="columns")
输出: