Home > Software design >  How to use the value in a variable as name to create a panda data frame?
How to use the value in a variable as name to create a panda data frame?

Time:07-16

In [182]: colname

Out[182]: 'col1'

In [183]: x= 'df_' colname

In [184]: x

Out[184]: 'df_col1'

May I know how to create a new pandas data frame with x, such that the new data frame's name would be df_col1

CodePudding user response:

Another way is to initialize a dictionary, and add keys containing dataframe as follows:

import pandas as pd

x = "your_column_name"
df_dict = {}
df_dict[x] = pd.DataFrame()

x = "your_new_column_name"
df_dict[x] = pd.DataFrame()

You can then change "x" anytime, and use the same idea to append dataframe in dictionary. To fetch dataframe back, you will then retrieve it back as you access dictionary.

CodePudding user response:

Use:

df_=pd.DataFrame({'a':[1,2,3]})
col_name = 'col1'
exec(f"df_{col_name}= df_")

Output:

enter image description here

CodePudding user response:

You can use the locals() function as given below,

>>> mydf
  col_A  col_B
0  1      4    
1  2      5    
2  3      6    
>>> colname = 'col1'
>>> locals()[f'df_{colname}'] = mydf.col_A
>>> df_col1
    0    1
    1    2
    2    3
Name: col_A, dtype: int64
  • Related