Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save dataframe as CSV in Python

I am trying to save the result of this code as a CSV file:

import pandas as pd

df = pd.DataFrame({'ID': ['a01', 'a01', 'a01', 'a01', 'a01', 'a01', 'a01', 'a01', 'a01', 'b02', 'b02','b02', 'b02', 'b02', 'b02', 'b02'],
                   'Row': [1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 3, 3, 3],
                   'Col': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 3, 1, 3, 1, 2, 3],
                   'Result': ['p', 'f', 'p', 'p', 'p', 'f', 'p', 'p', 'p', 'p', 'p', 'p', 'f', 'p', 'p', 'p']})


dfs = {}
for n, g in df.groupby('ID'):
    dfs[n] = g.pivot('Row', 'Col', 'Result').fillna('')
    print(f'ID: {n}')
    print(dfs[n])
    print('\n')
    print(dfs[n].stack().value_counts().to_dict())
    print('\n')

I found several methods and tried to save the output (dictionary form) into a CSV file, but without success. Any thoughts?

P.S. This is one of the methods I found, but I didn't know how to name the column based on my output?

with open("Output.csv", "w", newline="") as csv_file:
  cols = ["???????????"] 
  writer = csv.DictWriter(csv_file, fieldnames=cols)
  writer.writeheader()
  writer.writerows(data)
like image 343
Joanne Avatar asked Sep 18 '25 05:09

Joanne


2 Answers

df.to_csv('Output.csv', index = False)

For more details goto:

https://datatofish.com/export-dataframe-to-csv/

https://www.geeksforgeeks.org/saving-a-pandas-dataframe-as-a-csv/

like image 62
Kokul Jose Avatar answered Sep 19 '25 19:09

Kokul Jose


Use the method provided by pandas data frame abject

df.to_csv()
like image 32
Akash Maurya Avatar answered Sep 19 '25 21:09

Akash Maurya