从DataFrame python熊猫中写入csv。

时间:2022-10-07 22:54:36

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:

我编写了一个程序,在其中添加了两列,并编写了CSV文件的答案,但是当我只想要编写列的选择时,会出现错误。这是我的逻辑:

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

我怎么才能只写A、B和Sum的数据呢?我得到以下错误

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

2 个解决方案

#1


12  

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和B不再是列,因为您调用groupby(['A', 'B'])。相反,它们都是一个指数。试着去掉index=False,如下所示:

a.to_csv("test.csv", cols=['sum'])

#2


1  

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

如果您想将它写成excel文件,请使用此命令

writer = pd.ExcelWriter('output.xlsx')
data_frame.to_excel(writer,'Sheet1')
writer.save()

#1


12  

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和B不再是列,因为您调用groupby(['A', 'B'])。相反,它们都是一个指数。试着去掉index=False,如下所示:

a.to_csv("test.csv", cols=['sum'])

#2


1  

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

如果您想将它写成excel文件,请使用此命令

writer = pd.ExcelWriter('output.xlsx')
data_frame.to_excel(writer,'Sheet1')
writer.save()