Created
September 7, 2020 15:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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