Skip to content

Instantly share code, notes, and snippets.

@tchiavegatti
Last active November 15, 2021 20:57
Show Gist options
  • Save tchiavegatti/0e1eb6977653f9cb586ddee0a682db34 to your computer and use it in GitHub Desktop.
Save tchiavegatti/0e1eb6977653f9cb586ddee0a682db34 to your computer and use it in GitHub Desktop.
[Usefull stuff related to columns on Pandas] #pandas
# Find column index
df.columns.get_loc('col_name')
# The other way around (find column name using the index)
df.columns.get_values()[index]
# Find indices of multiple columns
def column_index(df, query_cols):
``` Get indices of multiple columns.
https://stackoverflow.com/a/38489403
```
cols = df.columns.values
sidx = np.argsort(cols)
return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]
# Alternative with list comprehension
[df.columns.get_loc(c) for c in cols if c in df]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment