Home > Net >  Python Pandas Writing Value to a Specific Row & Column in the data frame
Python Pandas Writing Value to a Specific Row & Column in the data frame

Time:07-22

I have a Pandas df of Stock Tickers with specific dates, I want to add the adjusted close for that date using yahoo finance. I iterate through the dataframe, do the yahoo call for that Ticker and Date, and the correct information is returned. However, I am not able to add that information back to the original df. I have tried various loc, iloc, and join methods, and none of them are working for me. The df shows the initialized zero values instead of the new value.

import pandas as pd
import yfinance as yf
from datetime import timedelta

# Build the dataframe
df = pd.DataFrame({'Ticker':['BGFV','META','WIRE','UG'], 
                   'Date':['5/18/2021','5/18/2021','4/12/2022','6/3/2019'],
                   })

# Change the Date to Datetime
df['Date'] = pd.to_datetime(df.Date)

# initialize the adjusted close
df['Adj_Close'] = 0.00 # You'll get a column of all 0s

# iterate through the rows of the df and retrieve the Adjusted Close from Yahoo
for i in range(len(df)):
  ticker = df.iloc[i]['Ticker']
  start = df.iloc[i]['Date']
  end = start   timedelta(days=1)

  # YF call
  data = yf.download(ticker, start=start, end=end)

  # Get just the adjusted close
  adj_close = data['Adj Close']

  # Write the acjusted close to the dataframe on the correct row
  df.iloc[i]['Adj_Close'] = adj_close

  print(f'i value is {i} and adjusted close value is {adj_close} \n')

print(df)

CodePudding user response:

The simplest way to do is to use loc as below-


# change this line
  df.loc[i,'Adj_Close'] =   adj_close.values[0]

CodePudding user response:

You can use:

def get_adj_close(x):
    # You needn't specify end param because period is already set to 1 day
    df = df = yf.download(x['Ticker'], start=x['Date'], progress=False)
    return df['Adj Close'][0].squeeze()

df['Adj_Close'] = df.apply(get_adj_close, axis=1)

Output:

>>> df
  Ticker       Date   Adj_Close
0   BGFV 2021-05-18   27.808811
1   META 2021-05-18  315.459991
2   WIRE 2022-04-12  104.320045
3     UG 2019-06-03   16.746983
  • Related