从给定 Pandas DataFrame 的列名中获取列索引
在本文中,我们将了解如何从 Dataframe 的列名中获取列索引。我们将使用Dataframe.columns 属性和Index.get_loc pandas模块在一起的方法。
Syntax: DataFrame.columns
Return: column names index
Syntax: Index.get_loc(key, method=None, tolerance=None)
Return: loc : int if unique index, slice if monotonic index, else mask
代码:让我们创建一个数据框:
Python3
# import pandas library
import pandas as pd
# dictionary
record = {'Math': [10, 20, 30,
40, 70],
'Science': [40, 50, 60,
90, 50],
'English': [70, 80, 66,
75, 88]}
# create a dataframe
df = pd.DataFrame(record)
# show the dataframe
print(df)
Python3
# import pandas library
import pandas as pd
# dictionary
record = {'Math': [10, 20, 30, 40, 70],
'Science': [40, 50, 60, 90, 50],
'English': [70, 80, 66, 75, 88]}
# give column name
col_name = "Science"
# find the index no
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
Python3
# import pandas library
import pandas as pd
# dictionary
record = {'Math': [10, 20, 30,
40, 70],
'Science': [40, 50, 60,
90, 50],
'English': [70, 80, 66,
75, 88]}
# create a dataframe
df = pd.DataFrame(record)
# give column name
col_name = "English"
# find the index no
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
输出:
示例 1:获取“Science”列的索引号。
Python3
# import pandas library
import pandas as pd
# dictionary
record = {'Math': [10, 20, 30, 40, 70],
'Science': [40, 50, 60, 90, 50],
'English': [70, 80, 66, 75, 88]}
# give column name
col_name = "Science"
# find the index no
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
输出 :
示例 2:获取“English”列的索引号。
Python3
# import pandas library
import pandas as pd
# dictionary
record = {'Math': [10, 20, 30,
40, 70],
'Science': [40, 50, 60,
90, 50],
'English': [70, 80, 66,
75, 88]}
# create a dataframe
df = pd.DataFrame(record)
# give column name
col_name = "English"
# find the index no
index_no = df.columns.get_loc(col_name)
print("Index of {} column in given dataframe is : {}".format(col_name, index_no))
输出 :