I want to convert this dictionary into data frame
dd = {'NFO:BANKNIFTY2210633600CE': {'instrument_token': 12355586, 'last_price': 3825.3}
,'NFO:BANKNIFTY2210633700CE': {'instrument_token': 12619522, 'last_price': 3213.45}}
here 'NFO:BANKNIFTY2210633600CE' this is also a value, and I want this as a value under column which name should be "Symbol", and I want "Last_price" as a column and under its value as a value.
Example -
Symbol Last_price
NFO:BANKNIFTY2210633600CE 3825.3
NFO:BANKNIFTY2210633700CE 3213.45
In this form, Please help me, to solve this problem.
CodePudding user response:
Create the dataframe from:
- a list of dicts, in the form {column1: value1, ...}
- a list of row index values
import pandas as pd
data = [
{'NFO:BANKNIFTY2210633600CE': {'instrument_token': 12355586, 'last_price': 3825.3}},
{'NFO:BANKNIFTY2210633700CE': {'instrument_token': 12619522, 'last_price': 3213.45}}
]
df = pd.DataFrame(data=[list(e.values())[0] for e in data], index=[list(e.keys())[0] for e in data])
print(df)
instrument_token last_price
NFO:BANKNIFTY2210633600CE 12355586 3825.30
NFO:BANKNIFTY2210633700CE 12619522 3213.45
CodePudding user response:
Assuming your data is a list of dictionaries, you can first use list comprehension to get the relevant data and cast them to pd.DataFrame:
lst = [{'NFO:BANKNIFTY2210633600CE': {'instrument_token': 12355586, 'last_price': 3825.3}}, {'NFO:BANKNIFTY2210633700CE': {'instrument_token': 12619522, 'last_price': 3213.45}}]
relevant_data = [(k, v['last_price']) for d in lst for k,v in d.items()]
df = pd.DataFrame(relevant_data, columns=['Symbol','Last_price'])
Output:
Symbol Last_price
0 NFO:BANKNIFTY2210633600CE 3825.30
1 NFO:BANKNIFTY2210633700CE 3213.45
CodePudding user response:
I assume initial data is a big dictionnary:
import pandas as pd
dd = {'NFO:BANKNIFTY2210633600CE': {'instrument_token': 12355586, 'last_price': 3825.3}
,'NFO:BANKNIFTY2210633700CE': {'instrument_token': 12619522, 'last_price': 3213.45}}
data = [(k, v['last_price']) for k,v in dd.items()]
df= pd.DataFrame(data, columns=['Symbol','Last_price'])
print(df)
Output is:
Symbol Last_price
0 NFO:BANKNIFTY2210633600CE 3825.30
1 NFO:BANKNIFTY2210633700CE 3213.45
