2017-02-23 102 views
1

的Python 2.7.11 //熊貓0.18.1操縱Dataframes與熊貓(Python)的

我有一個由數據集(CSV)與練習一個假想的酒類商店250級的項目。這些專欄包括「啤酒廠」,「標籤」,「年份」,「商店價格」,「MSRP」,「供應商價格」以及其他一些欄目。然而,對於這個問題,相關的部分是啤酒廠和商店價格(在結賬時查詢的當前價格)。

  Brewery Store Price 
104 Glenfiddich  109.99 
105 Glenfiddich  89.99 
108 Glenfiddich  114.99 
110 Glenfiddich  99.99 
119 Glenfiddich  169.99 

如果我上運行格蘭菲迪出售,我可以找到格蘭菲迪項目像這樣的東西:

df = pd.read_csv('liquorStore.csv')  
df.Brewery.str.contains('Glenfiddich') 

我知道如何找到格蘭菲迪產品,但我不知道如何改變數據框內的行的值。舉例來說,我想:

  1. 查找「格蘭菲迪」項目
  2. 調整「門市價」,以反映銷售/新價格(如10%)

注:我只是這樣做與熊貓練習

回答

2

您可以通過0.9使用locboolean indexing的選擇,然後多:

df.loc[df.Brewery == 'Glenfiddich', 'Store Price'] *= .9 

樣品:

print (df) 
     Brewery Store Price 
104 Glenfiddich  109.99 
105 Glenfiddich  89.99 
120  Another  100.00 

df.loc[df.Brewery == 'Glenfiddich', 'Store Price'] *= .9 
print (df) 
     Brewery Store Price 
104 Glenfiddich  98.991 
105 Glenfiddich  80.991 
120  Another  100.000 

另一種可能的解決方案是使用mask

df['Store Price'] = df['Store Price'].mask(df.Brewery == 'Glenfiddich', 
              df['Store Price'] * .9) 
print (df) 
     Brewery Store Price 
104 Glenfiddich  98.991 
105 Glenfiddich  80.991 
120  Another  100.000 
+1

是的,它是另一種解決方案,但如果檢查[這裏] (http://tomaugspurger.github.io/modern-1.html)'粗略的規則是任何時候你看到背對背的方括號,] [,你在尋求麻煩。將其替換爲.loc [...,...]並將被設置 – jezrael