简体   繁体   中英

Pandas: get column indices from a list of given names

Let say you have a pandas dataframe input and a list of column names. What is a good way to get a list of indices (column numbers) for the columns represented by those names?

I assume it'd be something along the lines of:

def get_col_indices(df, names):
    return [df.columns.index(name) for name in names]

Use Index.get_indexer :

def get_col_indices(df, names):
    return df.columns.get_indexer(names)

If you don't need them to be in the same order, you could use pd.Index.isin with np.flatnonzero

import numpy as np
np.flatnonzero(df.columns.isin(names))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM