2017-11-25 77 views
1

我有以下一些行的數據幀: -用熊貓來訪問元素的標量格式

restaurantName  cuisine  totalRating delivery 
Bindia Indian Bistro indian   4.0   Yes 
Bhoj Indian Cuisine indian   4.5   Yes 
Indian Roti House  indian   4.0   Yes 
Utsav     indian   4.0   Yes 

姑且稱之爲DF3。現在,在Python控制檯寫以下工作: -

df3[df3.restaurantName == 'Bindia Indian Bistro'].totalRating.item() 

,但是當我嘗試使用讀取文件如下這樣做: -

for line in f1: 
    restName = line.strip('\n') 
    print(restName) # to check if restaurant name is read fine 
    overallToRest = df3[df3.restaurantName == restName].totalRating.item() 

它提供了以下錯誤信息: -

Bindia Indian Bistro 
Traceback (most recent call last): 

    File "<ipython-input-12-cdb8b6170a65>", line 18, in prepare_final_file 
    overallToRest = df3.loc[df3['restaurantName'] == restName]['totalRating'].item() 

    File "C:\Users\myName\Anaconda3\lib\site-packages\pandas\core\base.py", line 814, in item 
    return self.values.item() 

ValueError: can only convert an array of size 1 to a Python scalar 

我試圖在Stack Overflow上搜索它,但找不到與我的問題相關的任何答案。請幫忙。提前致謝。

回答

0

restaurantName列中存在問題是重複的,所以篩選不僅返回一個值,而且還會返回更多值。

因此,可以只選擇一個值來標量,例如,首先由[0],然後檢查是否不emptySeriesif-else

overallToRest = df3.loc[df3.restaurantName == restName, 'totalRating'] 

overallToRest = 'no match' if overallToRest.empty else overallToRest.iat[0] 

另一種解決方案是drop_duplicates第一:

df3 = df3.drop_duplicates('restaurantName') 
overallToRest = df3.loc[df3.restaurantName == restName, 'totalRating'] 

overallToRest = 'no match' if overallToRest.empty else overallToRest.item() 

樣品:

print (df3) 
     restaurantName cuisine totalRating delivery 
0 Bindia Indian Bistro indian   4.0  Yes 
1 Bindia Indian Bistro indian   4.5  Yes 
2  Indian Roti House indian   4.0  Yes 
3     Utsav indian   4.0  Yes 



restName = 'Bindia Indian Bistro' 

overallToRest = df3.loc[df3.restaurantName == restName, 'totalRating'] 
print (overallToRest) 
0 4.0 
1 4.5 
Name: totalRating, dtype: object 

print (overallToRest.item()) 

ValueError: can only convert an array of size 1 to a Python scalar

overallToRest = 'no match' if overallToRest.empty else overallToRest.item() 
print (overallToRest) 
4.0 

restName = 'Bindia Indian Bistro' 

df3 = df3.drop_duplicates('restaurantName') 
print (df3) 
     restaurantName cuisine totalRating delivery 
0 Bindia Indian Bistro indian   4.0  Yes 
2  Indian Roti House indian   4.0  Yes 
3     Utsav indian   4.0  Yes 

overallToRest = df3.loc[df3.restaurantName == restName, 'totalRating'] 
print (overallToRest) 
0 4.0 
Name: totalRating, dtype: float64 

overallToRest = 'no match' if overallToRest.empty else overallToRest.item() 
print (overallToRest) 
4.0 
+0

我試圖實現此解決方案,但現在它給出了下面的錯誤: - '文件 「」,第24行,在prepare_final_file 打印(overallToRest.values [0]) IndexError:索引0超出軸0的大小爲0' 我認爲這是因爲文件中可能有一些餐館不在數據框中。爲了糾正這個問題,我申請了嘗試,例外塊來跳過這些餐館,但它仍然給出了同樣的錯誤。 –

+0

請檢查編輯答案。 – jezrael

+0

這個工作。謝謝 :) –