使用pandas(Python)操作数据帧
Python 2.7.11//0.18.1 我有一个虚构的数据集(csv)来练习一个有250种酒的假想酒类商店。这些栏目包括“啤酒厂”、“标签”、“年份”、“商店价格”、“MSRP”、“供应商价格”等。然而,对于这个问题,相关的部分是啤酒厂和商店价格(结账时查询的当前价格) 如果我在Glenfiddich上进行销售,我可以通过以下方式找到Glenfiddich产品:使用pandas(Python)操作数据帧,python,python-2.7,pandas,Python,Python 2.7,Pandas,Python 2.7.11//0.18.1 我有一个虚构的数据集(csv)来练习一个有250种酒的假想酒类商店。这些栏目包括“啤酒厂”、“标签”、“年份”、“商店价格”、“MSRP”、“供应商价格”等。然而,对于这个问题,相关的部分是啤酒厂和商店价格(结账时查询的当前价格) 如果我在Glenfiddich上进行销售,我可以通过以下方式找到Glenfiddich产品: df = pd.read_csv('liquorStore.csv') df.Brewery.str.contains('
df = pd.read_csv('liquorStore.csv')
df.Brewery.str.contains('Glenfiddich')
我知道如何找到Glenfiddich产品,但我不知道如何更改数据框中行的值。例如,我想:
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
另一种可能的解决方案是使用:
是的,这是另一种解决方案,但如果勾选
粗略规则是任何时候你看到背对背的方括号,][,你就会自找麻烦。用.loc[…,…]替换它,你就会被设置好。
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
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