📜  从给定 Pandas DataFrame 的列名中获取列索引

📅  最后修改于: 2022-05-13 01:55:06.079000             🧑  作者: Mango

从给定 Pandas DataFrame 的列名中获取列索引

在本文中,我们将了解如何从 Dataframe 的列名中获取列索引。我们将使用Dataframe.columns 属性和Index.get_loc pandas模块在一起的方法。

代码:让我们创建一个数据框:

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))

输出 :

英文栏索引号

英文栏索引号