Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

In R when you need to retrieve a column index based on the name of the column you could do

idx <- which(names(my_data)==my_colum_name)

Is there a way to do the same with pandas dataframes?

1 Answer

0 votes
by (107k points)

For that you can use .get_loc() function, refer the following code:

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns

Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")

Out[47]: 2

Usually access by name like (df["pear"], df[["apple", "orange"]], or df.columns.isin(["orange", "pear"]))

If you want to learn more about Pandas then visit this Python Course designed by the industrial experts.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...