Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write to csv from DataFrame python pandas

I wrote a program where i add two columns and write the answer to CSV file but I am getting error when I want to write only selection of columns . here is my logic:

import pandas as pd

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                           'foo', 'bar', 'foo', 'bar'],
                'B' : ['one', 'one', 'two', 'two',
                          'two', 'two', 'one', 'two'],
                'C' : [56, 2, 3, 4, 5, 6, 0, 2],
                'D' : [51, 2, 3, 4, 5, 6, 0, 2]})

grouped = df.groupby(['A', 'B']).sum()

grouped['sum'] = (grouped['C'] / grouped['D']) 
# print (grouped[['sum']])


a = pd.DataFrame(grouped)


a.to_csv("C:\\Users\\test\\Desktop\\test.csv", index=False, cols=('A','B','sum'))

how can i only write data of column A, B and Sum. I get the following error

Traceback (most recent call last):
  File "C:\Users\test\Desktop\eclipse\yuy\group.py", line 19, in <module>
    a.to_csv("C:\\Users\\test\\Desktop\\test.csv", index=False, cols=('A','B','sum'))
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1126, in to_csv
    date_format=date_format)
  File "C:\Python27\lib\site-packages\pandas\core\format.py", line 992, in __init__
    self.obj = self.obj.loc[:, cols]
  File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 1018, in __getitem__
    return self._getitem_tuple(key)
  File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 595, in _getitem_tuple
    self._has_valid_tuple(tup)
  File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 106, in _has_valid_tuple
    if not self._has_valid_type(k, i):
  File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 1100, in _has_valid_type
    (key, self.obj._get_axis_name(axis)))
KeyError: "[['A', 'B', 'sum']] are not in ALL in the [columns]"
like image 369
Developer Avatar asked Jan 18 '14 15:01

Developer


People also ask

How do I write to a CSV file in Python?

Write CSV files with csv.DictWriter() class can be used to write to a CSV file from a Python dictionary. Here, file - CSV file where we want to write to. fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file.

How do I append a DataFrame to a CSV file in Python?

To add a dataframe row-wise to an existing CSV file, we can write the dataframe to the CSV file in append mode by the parameter a using the pandas to_csv() function. Parameters: existing. csv: Name of the existing CSV file.

How do I save a Pandas file as a CSV?

In this article, we will learn how we can export a Pandas DataFrame to a CSV file by using the Pandas to_csv() method. By default, the to csv() method exports DataFrame to a CSV file with row index as the first column and comma as the delimiter.


2 Answers

A and B are no longer columns, since you called groupby(['A', 'B']). Instead they are both an index. Try leaving out the index=False, like this:

a.to_csv("test.csv", cols=['sum'])
like image 194
Matt Swain Avatar answered Sep 18 '22 18:09

Matt Swain


If you want to write it as an excel file, use this command

writer = pd.ExcelWriter('output.xlsx')
data_frame.to_excel(writer,'Sheet1')
writer.save()
like image 24
Wesam Na Avatar answered Sep 19 '22 18:09

Wesam Na