简体   繁体   中英

How to save to_csv with python

I'd like to have these items saved to_csv as one document

df = pd.DataFrame({'STREAM':['EAGLE','HAWK','HAWK','HAWK','EAGLE','HAWK','EAGLE'],'MAT':['A','D','F','D','C','C','E'],'KIS':['B','D','E','D','A','C','D'],'GEO':['B','C','E','E','F','A','B'],'BST':['C','E','D','D','B','F','C']})

columns = ["A",'A-',"B","C","D","E", "F"]
a = df.melt(id_vars=['STREAM'], value_vars=['MAT','KIS','BST','GEO']).pivot_table(index='STREAM', columns='value', values='variable', 
 aggfunc='count', fill_value=0, margins=True, margins_name='TOT').rename_axis(None)

print('SHOW FIRST TEXT HERE')
print(a)
print()
print('SHOW SECOND TEXT HERE')
print(df)

Such that my outcome would be something like this

       A  B  C  D  E  F  TOT
EAGLE  2  4  3  1  1  1   12
HAWK   1  0  3  6  4  2   16
TOT    3  4  6  7  5  3   28

SHOW SECOND TEXT HERE
STREAM MAT KIS GEO BST
EAGLE   A   B   B   C
HAWK    D   D   C   E
HAWK    F   E   E   D
HAWK    D   D   E   D
EAGLE   C   A   F   B
HAWK    C   C   A   F
EAGLE   E   D   B   C

Anybody with leads to this to assist

You can concatenate the two dataframes:

pd.concat([a, df], axis=0).to_csv('concatenated_dataframes.csv')

Although the differing shapes will mean you have NaNs filling the 'gaps'

Saving to csv usually means saving one table with the same headers. if you want to maintain the shapes of your dataframes, saving to MS Excel is a good option, since you can save them in differents tabs or spreadsheets .

If you like, you could use pickle . This would allow you to save each of your dataframes to the pickle, perhaps in a dictionary.

import pickle
dict = ('first': df, 'second': a)

pickle.dump(dict, open( "yourfile.pickle", "wb" ))

Then to open back up. pickle.load opens the file. In this case you stored two dataframes in one dictionary, so you will get a dictionary with two dataframes when you open/load the files from pickle.

new_dict = pickle.load( open( "yourfile.pickle", "rb" ) )

# To then get your dataframes, 
df = new_dict['first'] 
a = new_dict['second']

HDF5 is probably more complicated than you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM