Storing DataFrame names as. CSV files in Pandas

In [37]: blue = pd.DataFrame({'A': ['foo','foo','foo','bar','bar'], 'B': [4.0, 4.0, 5.0, 8.0, 8.0]})

In [38]: blue
Out[38]: 
     A  B
0  foo  4
1  foo  4
2  foo  5
3  bar  8
4  bar  8

In [39]: red = pd.DataFrame({'A': ['foo','foo','foo','bar','bar'], 'B': [np.nan, np.nan, np.nan, np.nan, np.nan]})

In [40]: red
Out[40]: 
     A   B
0  foo NaN
1  foo NaN
2  foo NaN
3  bar NaN
4  bar NaN

In [41]: for df in [blue, red]:
   ....:     df.to_csv(str(df))
   ....:     

In [42]: !ls
     A  B?0  foo  4?1  foo  4?2  foo  5?3  bar  8?4  bar  8       A   B?0  foo NaN?1  foo NaN?2  foo NaN?3  bar NaN?4  bar NaN  postinstall.sh  vagrant

      

I have some DataFrames. I iterate over each DataFrame to work on them. At the end of the loop, I want to save each DataFrame as a CSV file named DataFrame. I know it is generally difficult to compress a variable name in Python, but I must be thinking that I am missing something obvious here. There is no "name" attribute for DataFrames, so what should I do?

+3


source to share


1 answer


You can just add the attribute to df like any other python object that has an attribute __dict__

and use it later:

In [2]:

blue.name = 'blue'
red.name = 'red'
df_list = [blue, red]
for df in df_list:
    print(df.name)
    df.to_csv(df.name + '.csv')
blue
red

      

Better yet, for convenience, you can save the csv name and use it later:



In [5]:

blue.name = 'blue'
blue.csv_path = 'blue.csv'
red.name = 'red'
red.csv_path = 'red.csv'
df_list = [blue, red]
for df in df_list:
    print(df.name)
    print(df.csv_path)
    df.to_csv(df.csv_path)
blue
blue.csv
red
red.csv

      

EDIT As @Jeff pointed out, the attributes won't persist in most operations on df when a copy of df is returned, and those attributes won't be copied, so keep that in mind.

+4


source







All Articles