To obtain the column number(s) of an entry/entries in Pandas, you can use the .get_loc()
method. For example:
import pandas as pd # create a sample dataframe df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # get the column number of column 'B' col_num_B = df.columns.get_loc('B') # get the column numbers of columns 'B' and 'C' col_nums_B_C = [df.columns.get_loc(c) for c in ['B', 'C']]
In this example, col_num_B
would be 1
(since column 'B' is the second column), and col_nums_B_C
would be [1, 2]
(since columns 'B' and 'C' are the second and third columns, respectively).
Asked: 2023-06-19 19:06:41 +0000
Seen: 11 times
Last updated: Jun 19 '23