Louis
Louis

Reputation: 307

Save file while keeping the same formatting in pandas

I have a program which gives me stock info when I give it an input file.

This file iterates every row and does some simple calculations.

for index, row in df.iterrows():
    ticker=row['Ticker']

    ticker_stock = yf.Ticker(ticker.strip())
    data = ticker_stock.history()
    row['Price'] = (data.tail(1)['Close'].iloc[0])

    #Print Stock Name
    stockName = ticker_stock.info['longName']
    print(stockName)

    print(row['Ticker'], row['Price'])

    row['Value'] = row['BuyPrice'] * row['BuyAmount']
    print(row['Value'])

    row.to_csv('balance.csv')

I want to save the file after doing the calculations, but the format is different.

Here is an example of the input file:

0,Ticker,BuyPrice,BuyAmount,Value,Price
1,MSFT,4832,4,43,456

And here is the output file created by the program.

,2
Ticker,MSFT
BuyPrice,4832.0
BuyAmount,4
Value,19328.0
Price,215.80999755859375

Is there a way to save the file while keeping the original format? It is clear that if I want to rerun the program it will not work. Since the rows are now columns.

Upvotes: 0

Views: 527

Answers (1)

gtomer
gtomer

Reputation: 6564

Here is the corrected code:

for index, row in df.iterrows():
    ticker=row['Ticker']

    ticker_stock = yf.Ticker(ticker.strip())
    data = ticker_stock.history()
    df.loc[index, 'Price'] = (data.tail(1)['Close'].iloc[0])

    #Print Stock Name
    stockName = ticker_stock.info['longName']
    print(stockName)

    print(df.loc[index, 'Ticker'], df.loc[index, 'Price'])

    df.loc[index, 'Value'] = row['BuyPrice'] * row['BuyAmount']
    print(df.loc[index, 'Value'])

df.to_csv('balance.csv')

Changes:

  1. take the to_csv outside the loop
  2. you to_csv just once and the DF
  3. updating value using df.loc[index, ]

Upvotes: 2

Related Questions