2014-01-18 121 views
8

我寫了一個程序,其中我添加了兩列並將答案寫入CSV文件,但當我只想寫入列選擇時出現錯誤。 這裏是我的邏輯:從DataFrame寫入csv python熊貓

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

我怎麼能只寫列A,B和點心的數據。 我收到以下錯誤

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

回答

10

A和B都不再列,因爲你叫groupby(['A', 'B'])。相反,它們都是索引。嘗試留出了index=False,就像這樣:

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

你也可以使用'分組= df.groupby(['A ','B'],as_index = False).sum()'以防止A和B被視爲分組 – dlm

+0

'.to_csv'中的索引似乎現在不推薦使用或者我的腳本說'AttributeError:DataFrame對象沒有屬性'to_csv'。我個人一直在使用'.toCSV'與我的數據框,它似乎工作正常。 – Blairg23

1

如果你想將它寫成一個Excel文件,使用此命令

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