简体   繁体   中英

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]"

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'])

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()

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