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?
You can get the column index from the column name in Pandas using DataFrame. columns. get_loc() method. DataFrame.
Sometimes you may have an column index and wanted to get column name by index in pandas DataFrmae, you can do so by using DataFrame. columns[idx] . Note that index start from 0.
Selecting columns based on their name This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.
Sure, you can use .get_loc()
:
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
although to be honest I don't often need this myself. Usually access by name does what I want it to (df["pear"]
, df[["apple", "orange"]]
, or maybe df.columns.isin(["orange", "pear"])
), although I can definitely see cases where you'd want the index number.
Here is a solution through list comprehension. cols is the list of columns to get index for:
[df.columns.get_loc(c) for c in cols if c in df]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With