操纵Dataframes与熊猫(Python)的

操纵Dataframes与熊猫(Python)的

问题描述:

的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%)

注:我只是这样做与熊猫练习

您可以通过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