0

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

Ptar
  • 374
  • 4
  • 16
  • 1
    Does this answer your question? [Multiple pandas.dataframe to one csv file](https://stackoverflow.com/questions/30829748/multiple-pandas-dataframe-to-one-csv-file) – Iteeeh May 18 '20 at 18:54
  • Your dataframes are different shapes. This will make it challenging to save to one csv. Why is one file necessary? Also, consider excel, pickle, or hdf5. – run-out May 18 '20 at 19:04
  • @run-out, expound on this excel, pickle and the hdf5 – Ptar May 18 '20 at 19:14

2 Answers2

1

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'

SimonR
  • 1,774
  • 1
  • 4
  • 10
1

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.

run-out
  • 3,114
  • 1
  • 9
  • 25
  • How do I open a pickle file?? How do I add space between the dataframes in the file???? – Ptar May 18 '20 at 19:57