簡體   English   中英

用熊貓處理數據框(Python)

[英]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產品,但不知道如何更改數據框內行的值。 例如,我要:

  1. 查找“ Glenfiddich”商品
  2. 調整“商店價格”以反映銷售價格/新價格(例如,折價10%)

注意:我只是在做熊貓練習。

您可以將locboolean 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM