0

I would like to fill each row of a column of my dataframe based on the entries in 2 other columns, in particular I want to fill each row with the corresponding stock price of the corresponding ticker for that stock and the date, like so

dict1 = [{'ticker': 'AAPL','date': date(2016, 3, 1),'Price': 'NaN'},
         {'ticker': 'MSFT','date': date(2017, 12, 1), 'Price': 'NaN'}]

 df1 = pd.DataFrame(dict1)
 df1.index=df1['ticker']
 df1.loc['AAPL','Price'] = web.DataReader(df1.loc['AAPL','ticker'], 'iex', df1.loc['AAPL','date'], df1.loc['AAPL','date']).close[0]

I am struggling to find a way to automate this with a for loop, apply, or map. Can anyone suggest an approach?

I have asked a similar question, where 'map' worked (for just 1 column) but I am not sure how to extend that to 2 reference columns.

Filling a pandas column based on another column

Note, the function used to pull the name comes from here:

import pandas_datareader.data as web

Tartaglia
  • 949
  • 14
  • 20

1 Answers1

1

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html

import pandas as pd
from datetime import date

import pandas_datareader.data as web


def lookup_price(row):
    return web.DataReader(row['ticker'], 'iex', row['date']).close[0]


def main():
    dict1 = [
        {'ticker': 'AAPL', 'date': date(2016, 3, 1)},
        {'ticker': 'MSFT', 'date': date(2017, 12, 1)},
    ]
    df1 = pd.DataFrame(dict1)
    df1['price'] = df1.apply(lookup_price, axis='columns')
    print(df1)


if __name__ == '__main__':
    main()
lexual
  • 46,172
  • 2
  • 15
  • 14
  • Perfect, this is awesome!!! I also love the if __name__ == '__main__': main(). I had to look that up, but that will be useful to me!! – Tartaglia Dec 21 '18 at 21:25