Home > OS >  How Can I Convert Panda Dataframe to Dict By Adding Header in Item
How Can I Convert Panda Dataframe to Dict By Adding Header in Item

Time:12-27

https://i.stack.imgur.com/TEFp0.png

Hi everyone, I have a dataframe as in the picture from yfinance. I will use it on Django Rest Framework. So I need to change the format and make small changes...

Basically, I want to convert it to dict but i need timestamp in items as below... If someone can help me i would be appreciated...

{
   {
     'datetime': '22-09-30'
     'TotalRevenue': 'xxxx'
     'CostOfRevenue': 'xxxx'
   },
   {
     'datetime': '22-06-30'
     'TotalRevenue': 'xxxx'
     'CostOfRevenue': 'xxxx'
   },
   {
     'datetime': '22-03-30'
     'TotalRevenue': 'xxxx'
     'CostOfRevenue': 'xxxx'
   },
   {
     'datetime': '21-12-30'
     'TotalRevenue': 'xxxx'
     'CostOfRevenue': 'xxxx'
   }
}

I'm not so familiar with Panda so i tried a few things...

stockTicker = yf.Ticker(symbol   '.IS')

    stockIncomeQuarterlyPanda = stockTicker.quarterly_income_stmt

    stockIncomeQuarterlyChangeNan = stockIncomeQuarterlyPanda.fillna(0)

    stockIncomeQuarterlyPandaToDict = stockIncomeQuarterlyChangeNan.to_dict()

    stockIncomeQuarterly = stringify_keys(stockIncomeQuarterlyPandaToDict)

This is my code now...

CodePudding user response:

The output you showed is not a valid dict. If you want an list of dicts instead:

[{"date": col, **df[col].to_dict()} for col in df.columns]
  • Related