2017-07-26 136 views
0

我有一個對象數組。我試圖循環訪問該數組並創建一個新的數據框,然後將其保存到電子表格中。Python3熊貓 - 基於對象數組創建新的數據框

我的目標變量是這樣的:

def __init__(self, question, total): 
    self.question = str(question) 
    self.total = float(total) 
    self.answers = {} 

question是疑問句

total的字符串是一個數字的總票數的問題,收到

answers是包含字典數據如:{'Yes': 5, 'No': 2, 'Maybe': 1},答案選擇的字符串和收到答案的選票數量

我試圖循環訪問Question對象的q_array,追加問題和總數,然後在下面的for循環中查看答案項目並將其附加到其他行上。

下面是所需的輸出/表:

Question    Answer Total Percent 
What color is the sky?   22  
         Red  8  36.4% 
         Green  2  9.1% 
         Blue  12  54.5% 

這裏是我當前的代碼:

writer = pd.ExcelWriter('master.xlsx') 

sdf = pd.DataFrame(columns=('Question', 'Answer', 'Total', 'Percent')) 
for data in q_array: 
    sdf.append({'Question': data.get_question(), 'Total': data.get_total()}, ignore_index=True) 
    for answer, number in data.get_answers().items(): 
     sdf.append({'Answer': answer, 'Total': number, 'Percent': number_to_percent(number, data.get_total())}, ignore_index=True) 

sdf.to_excel(writer, 'stats', index=False) 

writer.save() 

我試圖用.append()添加新行並選擇行中有哪些數據。但是,當我打印sdf它是空的,並在電子表格中它有列,但其餘的數據丟失。我究竟做錯了什麼?感謝您提供的任何幫助!

回答

0

答案很簡單:而不是sdf.append()我需要設置數據框等於追加,因此sdf = sdf.append()

下面是正確的代碼:

writer = pd.ExcelWriter('master.xlsx') 

sdf = pd.DataFrame(columns=('Question', 'Answer', 'Total', 'Percent')) 
for data in q_array: 
    sdf = sdf.append({'Question': data.get_question(), 'Total': data.get_total()}, ignore_index=True) 
    for answer, number in data.get_answers().items(): 
     sdf = sdf.append({'Answer': answer, 'Total': number, 'Percent': number_to_percent(number, data.get_total())}, ignore_index=True) 

sdf.to_excel(writer, 'Stats', index=False) 

writer.save() 
相關問題