2017-04-26 101 views
0

我已經將一個數據框轉換爲一個字典,並且在'for'函數中使用了其中一個字典值,但是它給了我以下錯誤?從數據框字典中取值

df = 
Metal       Medium Carbon Steel 
Max Compressive Stress/MPa     305 
Cost per m^3/$        4301 
I/mm^4        3.27869e+07 
inner_radius_quarted     5.82544e+07 
inner_radius/mm       87.3639 
thickness/mm        12.6361 
volume/mm^3        12636.1 
cost/$         0.0543477 

a1 = df.to_dict() 

P = [P -1,P +1] 

for i in P: 
    x = (i * L * y)/(a1[1][u'I/mm^4'] * 4) 
if x > a1[1][u'Max Compressive Stress/MPa']: 
    print "A point load of", i, ", will break the beam" 
else: 
    print "A point load of", i, ", will not break the beam" 



KeyError         Traceback (most recent call last) 
<ipython-input-255-8d9325dc6d75> in <module>() 
     2 
     3 for i in P: 
----> 4  x = (i * L * y)/(a1[1][u'I/mm^4'] * 4) 
     5  if x > a1[1][u'Max Compressive Stress/MPa']: 
     6   print "A point load of", i, ", will break the beam" 

KeyError: 1 
+0

究竟'P = [P-1,P + 1]'呢? –

+0

它採用一個先前定義的P值,並列出P + 1和P-1 –

回答

1

你看過a1。它並沒有接近你所需要的。

{'Medium Carbon Steel': {'Cost per m^3/$': 4301.0, 
    'I/mm^4': 32786900.0, 
    'Max Compressive Stress/MPa': 305.0, 
    'cost/$': 0.054347699999999999, 
    'inner_radius/mm': 87.363900000000001, 
    'inner_radius_quarted': 58254400.0, 
    'thickness/mm': 12.636100000000001, 
    'volume/mm^3': 12636.1}} 

嘗試

a1 = df['Medium Carbon Steel'].to_dict() 

P = [P -1,P +1] 

for i in P: 
    x = (i * L * y)/(a1['I/mm^4'] * 4) 
if x > a1['Max Compressive Stress/MPa']: 
    print("A point load of", i, ", will break the beam") 
else: 
    print("A point load of", i, ", will not break the beam")