Joanne
Joanne

Reputation: 503

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)

Upvotes: 4

Views: 21085

Answers (3)

Kokul Jose
Kokul Jose

Reputation: 1732

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/

Upvotes: 7

awadhesh pathak
awadhesh pathak

Reputation: 121

You can use df.to_csv() to convert your data to csv.

Upvotes: 0

Akash Maurya
Akash Maurya

Reputation: 404

Use the method provided by pandas data frame abject

df.to_csv()

Upvotes: 3

Related Questions