问题
I have the following dataframe called df1
,
country ticker price
0 US MSFT 105.32
1 US AAPL
2 GERMANY NSU.DE 10.42
3 SG D05.SI
4 AUS WOW.AX
I have a function called price_get
that looks like this
def price_get(ticker):
price = somefunction
return price
The function has to go online to look up the value so it takes a few seconds to run each time.
I want to only use this function on the cells which don't have a price in them, (price cells are empty).
So the function would only be used on rows 1, 3 & 4 in this dataframe and update the price values in them to look something like this
country ticker price
0 US MSFT 105.32
1 US AAPL 150.22
2 GERMANY NSU.DE 10.42
3 SG D05.SI 23.44
4 AUS WOW.AX 12.33
How do I apply the price_get function to only the price rows which are empty, use the ticker column string as an input, and update the price column?
回答1:
You should use Boolean Masking for this task, example:
df.loc[df['price'].isna(), 'ticker'] = df.loc[df['price'].isna(), 'ticker'].apply(price_get)
回答2:
Let us do filter then apply your function
df.price.fillna(df.loc[df.price.isnull(),'ticker'].apply(yourfunction),inplace=True)
来源:https://stackoverflow.com/questions/61647693/how-to-update-dataframe-cells-using-function-return-values