Skip to content

Instantly share code, notes, and snippets.

@ReneHamburger1993
Created September 7, 2020 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReneHamburger1993/99f47807fc06f47df2e6df6b2ea55d91 to your computer and use it in GitHub Desktop.
Save ReneHamburger1993/99f47807fc06f47df2e6df6b2ea55d91 to your computer and use it in GitHub Desktop.
[pandas Columns or Index] add new level #python #pandas #columns #index #add #level #multilevel
# pandas stuff
```python
#add a level in the columns below all current ones
df.columns = pd.MultiIndex.from_product([df.columns, ['C']])
```
```python
# enter it in between
df.columns = pd.MultiIndex.from_tuples(\
map(lambda x: (x[0], 'A', *x[1:]), df.columns))
```
```
# test for the above:
import pandas as pd
df = pd.DataFrame({"col1":[2,3,5],"col2":["abc","cdef","sdgae"]})
display(df)
df.columns = pd.MultiIndex.from_product([df.columns, ['C']])
display(df)
df.columns = pd.MultiIndex.from_tuples(\
map(lambda x: (x[0], 'A', *x[1:]), df.columns))
display(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment