Python是进行数据分析的优秀语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。 熊猫 是这些软件包中的一个,使导入和分析数据变得更加容易。 熊猫 set_index() 是一种将列表、系列或数据帧设置为数据帧索引的方法。也可以在制作数据帧时设置索引列。但有时一个数据帧由两个或多个数据帧组成,因此可以使用此方法更改以后的索引。 语法:
数据帧。设置索引(键,drop=True,append=False,inplace=False,verify_integrity=False)
参数:
钥匙: 列名或列名列表。 放下: 布尔值,如果为True,则删除用于索引的列。 附加: 如果为True,则将列追加到现有索引列。 就地: 如果为True,则在数据帧中进行更改。 验证_的完整性: 如果为True,则检查新索引列是否存在重复项。
要下载使用的CSV文件,请单击 在这里 代码#1: 更改索引列 在本例中,First Name column已成为数据帧的索引列。
Python3
# 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参数用于删除列,append参数用于将传递的列附加到已存在的索引列。
Python3
# 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: 设定一个 浮柱 作为数据帧中的索引
Python3
# 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 |
输出:
在上面的示例中,我们设置了列的 阿古马克 ‘作为数据帧的索引。
代码#4: 背景 三列 像 多索引 在数据帧中
Python3
# 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 |
输出:
在上面的示例中,我们设置了列的 名称 ‘, ‘ 城市 ‘和’ 身份证件 ‘作为数据帧的多索引。