简体   繁体   中英

How can I extract each dict from a list and put it into dataframe?

I have a list like this: ['{"a":0,"b":1,"c":2},{"a":1,"b":2,"c":3},{"a":1,"b":2,"c":3}']

It only has one item on the list. I would like to extract each dictionary and put them into one Dataframe.

use loads from the json module to make this a real list of dictionaries. then just pass it to DataFrame():

from json import loads
from pandas import DataFrame

weird_list = ['{"a":0,"b":1,"c":2},{"a":1,"b":2,"c":3},{"a":1,"b":2,"c":3}']

real_list = loads(f"[{weird_list[0]}]")

then either pass the whole list to DataFrame if you want them in one place

three_dct_df = DataFrame(real_list)
three_dct_df
   a  b  c
0  0  1  2
1  1  2  3
2  1  2  3

or loop over it creating individual DataFrames. But if using scalar values you have to pass an index so..

for lst in real_lst:
    print(DataFrame(lst, index= [0]))

   a  b  c
0  0  1  2

   a  b  c
0  1  2  3

   a  b  c
0  1  2  3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM