2017-01-03 81 views
1

我在問這個問題,因爲我堅持了一段時間,並找不到任何合適的解決方案在這個社區或任何地方。 我有一個熊貓數據框,我需要創建一個字典的方式是,一列的第一個值形成第一個鍵值對,其餘的形成鍵值對的其餘部分。數據幀我有看起來像這樣如何從熊貓數據框中列的第二個值追加到字典

created     count 
0 2016-12-31 00:00:00  34 
1 2016-01-31 00:00:00  1 
2 2016-02-31 00:00:00  5 

現在所需要的輸出是這樣的

return { 
'avg_active_percentage' : 79.2, 
'past_trend': '39,34,23,12' 
} 

使用ILOC []功能我設法解決這個問題的第一部分。第二部分是棘手的部分。還稍微計算一下做是爲了得到一個百分比值,然後舍入到最接近的十進制值

a['count']= a['count']*100/total_number_users 
a['count']=a['count'].round(1) 
b=a['count'].iloc[0] 
b=str('%.2f'% b) 
result={'average_active_percentage': b} 
i=1 
c=[] 
c=a['count'].iloc[i] 
while count in a['count']: 
    i=i+1 
    c.append(a['count'].iloc[i].round(1))  
result['past trend']=c 
result 

但是我對上面的代碼說

TypeError: unsupported operand type(s) for /: 'str' and 'int' 
+0

什麼是a ['count']。dtype'? – jezrael

+1

看起來您正試圖對包含字符串的變量執行除法。另外,將來請發佈完整的堆棧跟蹤。這樣可以更輕鬆地立即縮小問題的範圍(例如,您遇到錯誤的確切路線)。 –

回答

1

得到一個錯誤,我認爲你可以使用:

#cast to numeric, if problematic value replace by NaN 
a['count'] = pd.to_numeric(a['count'], errors='coerce') 

total_number_users = 250 
#cast to string, create list with all values without first 
L = a['count'].round(1).astype(str).iloc[1:].tolist() 
print (L) 
['1', '5'] 
#create string with list 
past_trend = ','.join(L) 
print (past_trend) 
1,5 

a['count']= a['count']*100/total_number_users 
a['count']=a['count'].round(1) 
b=a['count'].iloc[0] 
b=str('%.2f'% b) 

result={'average_active_percentage': b} 
#print (result) 

result['past trend']=past_trend 
print (result) 
{'average_active_percentage': '13.60', 'past trend': '1,5'} 
+0

謝謝你jezrael .. –

相關問題