Python Pandas DataFrame.set_index()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据更加容易。
Pandas set_index()是一种设置列表、系列或数据框架作为数据框架索引的方法。索引列也可以在制作一个数据框架时设置。但有时一个数据框是由两个或更多的数据框组成的,因此后来可以用这个方法改变索引。
语法:
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
参数:
keys:列名或列名的列表。
drop: 布尔值,如果为真,将删除用于索引的列。
append: 如果为真,将该列添加到现有的索引列中。
inplace:在数据框架中进行更改,如果是真的。
verify_integrity:检查新的索引列是否重复,如果是的话。
代码#1:更改索引栏
在这个例子中,名字列已经成为数据框架的索引列。
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# setting first name as index column
data.set_index("First Name", inplace = True)
# display
data.head()
输出:
如输出图片所示,早期的索引列是一系列的数字,但后来被替换成了名字。
操作前-
操作后-
代码#2:多个索引列
在这个例子中,两个列将被作为索引列。Drop参数用于Drop列,append参数用于将通过的列追加到已经存在的索引列中。
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# setting first name as index column
data.set_index(["First Name", "Gender"], inplace = True,
append = True, drop = False)
# display
data.head()
输出:
如输出图片所示,该数据有3个索引列。
代码#3:在Pandas数据框架中设置一个单一的浮点列作为索引
# importing pandas library
import pandas as pd
# creating and initializing a nested list
students = [['jack', 34, 'Sydeny', 'Australia',85.96],
['Riti', 30, 'Delhi', 'India',95.20],
['Vansh', 31, 'Delhi', 'India',85.25],
['Nanyu', 32, 'Tokyo', 'Japan',74.21],
['Maychan', 16, 'New York', 'US',99.63],
['Mike', 17, 'las vegas', 'US',47.28]]
# Create a DataFrame object
df = pd.DataFrame(students,
columns=['Name', 'Age', 'City', 'Country','Agg_Marks'],
index=['a', 'b', 'c', 'd', 'e', 'f'])
# here we set Float column 'Agg_Marks' as index of data frame
# using dataframe.set_index() function
df = df.set_index('Agg_Marks')
# Displaying the Data frame
df
输出 :
在上面的例子中,我们将列 “Agg_Marks “作为数据框架的索引。
代码#4:在Pandas DataFrame中设置三列为多指标。
# importing pandas library
import pandas as pd
# creating and initializing a nested list
students = [['jack', 34, 'Sydeny', 'Australia',85.96,400],
['Riti', 30, 'Delhi', 'India',95.20,750],
['Vansh', 31, 'Delhi', 'India',85.25,101],
['Nanyu', 32, 'Tokyo', 'Japan',74.21,900],
['Maychan', 16, 'New York', 'US',99.63,420],
['Mike', 17, 'las vegas', 'US',47.28,555]]
# Create a DataFrame object
df = pd.DataFrame(students,
columns=['Name', 'Age', 'City', 'Country','Agg_Marks','ID'],
index=['a', 'b', 'c', 'd', 'e', 'f'])
# Here we pass list of 3 columns i.e 'Name', 'City' and 'ID'
# to dataframe.set_index() function
# to set them as multiIndex of dataframe
df = df.set_index(['Name','City','ID'])
# Displaying the Data frame
df
输出 :
在上面的例子中,我们将列’姓名’、’城市’和’ID’设置为数据框的多重索引。