Home > front end >  Splitting dataframe by column name and name each as a column name
Splitting dataframe by column name and name each as a column name

Time:09-21

I have a dataframe that looks like below

    A      B       C       D      E
0 Orange  Dad   X Eyes    3d     Navy
1 pink    Mum    Bored    ooo    NaN
2 Yellow  NaN    Sad      Gray   NaN

and I'm trying to split this dataframe into each column by its column name and name splitted column as df_column_name.

So my desire output is

>>> df_A

    A
0 Orange
1 pink
2 Yellow

>>> df_B

   B
0 Dad
1 Mum
2 NaN

So I tried below code

d={f'df_{i}': for i in df}

which returned an error saying

File "/var/folders/jd/lh_mnln92n17ysg8grr0000gn/T/ipykernel_2633/2946580.py", line 1
    d={f'df_{i}': for i in df}
                                        ^
SyntaxError: invalid syntax

CodePudding user response:

Create dictionary of DataFrames:

d= {i:df[[i]] for i in df}
print (d['A'])
        A
0  Orange
1    pink
2  Yellow

It is not recommended, but possible:

for i in df:
    globals()[f'df_{i}'] =  df[[i]]

print (df_A)
        A
0  Orange
1    pink
2  Yellow
  • Related