简体   繁体   中英

Converting Pandas dataframe to specific JSON structure

I am interested in obtaining a specific json structure from Pandas Dataframes that I haven't been able to achieve from anywhere.

The code

html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[-1]
print(df)
#print(df.to_json())

The Output

  Howe center       1st & river        4th & river  
5    8:37 AM            8:50 AM            8:52 AM        
6    8:57 AM            9:10 AM            9:12 AM         
7    9:17 AM            9:30 AM            9:32 AM         

The desired JSON

{
 "Howe Center":["8:37 AM", "8:57 AM", "9:17 AM"],
 "1st & river":["8:50 AM", "9:10 AM", "9:30 AM"],
 "4th & river":["8:52 AM", "9:12 AM", "9:32 AM"]
}

What I Get

{
 "Howe Center":{"0":"8:37 AM,"1":"8:57 AM",...},
 "1st & river":{"0":"8:50 AM, ...}

Any help is appreciated! Thanks

Use:

#import json
my_json=json.dumps(df.to_dict('list'))
print(my_json)

{"How ecenter": ["8:37 AM", "8:57 AM", "9:17 AM"], "1st & river": ["8:50 AM", "9:10 AM", "9:30 AM"], "4t & river": ["8:52 AM", "9:12 AM", "9:32 AM"]}

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