• notice
  • Congratulations on the launch of the Sought Tech site

How to normalize JSON archive to Pandas dataframe

I have a JSON file called stocks.json as shown below (note in source fileMissing square brackets):

{"MSFT": {"exchange": "Nasdaq", "price": 275.79}, "FB": {"exchange": "Nasdaq", " price": 320.22}, "TSLA": {"exchange": "Nasdaq" , "price": 990.83}, "GE": {"exchange": "Nasdaq ", "price": 83.20}}

I want to convert this data to a Pandas data box like this: font>

symbol exchange price
MSFT Nasdaq 275.79
FB Nasdaq 320.22
TSLA Nasdaq 990.83
GE NYSE 83.20

My attempt is:

import pandas as pd

stock_data=pd.read_json('stocks.json', lines=True)
stock_data_normalized=pd.json_normalize(stock_data)

Unfortunately, I get the following when callingstock_data_normalized:

0
1
2
3

Any help would be greatly appreciated.Thanks!

uj5u.com enthusiastic netizens replied:

You can just use pd.DataFrame()Constructor, then transpose and reset index: p>

df=pd.DataFrame(d).T.reset_index().rename({'index': 'symbol'}, axis=1)

Output:

>>> df
  symbol exchange price
0 MSFT Nasdaq 275.79
1 FB Nasdaq 320.22
2 TSLA Nasdaq 990.83
3 GE Nasdaq 83.2

Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

cheap lipitor & lt;a href="https://lipiws.top/"& gt;lipitor 40mg brand& lt;/a& gt; buy atorvastatin pills for sale

Gclcch

2024-03-07

Leave a Reply

+