[英]Manipulating Dataframes with pandas (Python)
Python 2.7.11 //熊猫0.18.1
我有一个虚构的数据集(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
如果我在Glenfiddich上进行销售,则可以通过以下方式找到Glenfiddich的商品:
df = pd.read_csv('liquorStore.csv')
df.Brewery.str.contains('Glenfiddich')
我知道如何找到Glenfiddich产品,但不知道如何更改数据框内行的值。 例如,我要:
注意:我只是在做熊猫练习。
您可以将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.