使用pandas操作数据帧(Python)

时间:2017-02-23 07:11:45

标签: python python-2.7 pandas

Python 2.7.11 // Pandas 0.18.1

我有一个组成的数据集(csv)来练习一个有250个项目的虚构酒类商店。这些专栏涵盖'啤酒厂','标签','年','商品价格','建议零售价','供应商价格'等等。但是对于这个问题,相关的部分是啤酒厂和商店价格(结账时查询的当前价格)。

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

如果我在Glenfiddich进行销售,我可以找到Glenfiddich项目,如下所示:

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

我知道如何找到Glenfiddich产品,但我不知道如何更改数据框中行的值。例如,我想:

  1. 查找'Glenfiddich'项目
  2. 调整'商品价格'以反映促销/新价格(例如10%折扣)
  3. 注意:我这样做是为了练习 pandas

1 个答案:

答案 0 :(得分:2)

您可以loc使用boolean indexing进行选择,然后使用0.9进行多次采访:

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
相关问题