简体   繁体   English

使用熊猫将excel转换为Json文件

[英]Convert excel to Json file using pandas

["

I'm trying to convert attached sample csv to json file.<\/i>我正在尝试将附加的示例 csv 转换为 json 文件。<\/b> It is workng fine for single server but finding issue when it is more than 1 server excel example<\/a><\/i>它适用于单台服务器,但是当它超过 1 台服务器时会发现问题excel 示例<\/a><\/b><\/p>

,How many servers are required?*  ,3,,,

,,,,,

,,,,,

,,,Server 1,Server 2,Server 3

,,,,,

1,OS Type*,,Windows,Unix,Windows

,,,,,

2,OS Version*,,Windows Server 2019,RHEL 7.9,Windows Server 2019

,,,,,

3,Server environment*,,Non-production,Non-production,Non-production
import pandas as pd


# We read the file and remove empty rows and columns.
df = pd.read_csv('test.csv').dropna(how='all', axis=1).dropna(how='all')

# We remove the unnecessary column and replace the remaining none with 0.
df = df.drop(df.columns[[0]], axis=1).fillna(0)

# We replace the indexes and names of rows and columns with the required ones and delete the now unnecessary ones.
df = df.rename(columns=df.iloc[0]).drop(df.index[0])
df = df.rename(index=df[0]).drop(df.columns[[0]], axis=1)

# We write the result to a file with the required orientation.
result = df.to_json('test.json', orient="columns")

{"Server 1":{"OS Type*":"Windows","OS Version*":"Windows Server 2019","Server environment*":"Non-production"},
"Server 2":{"OS Type*":"Unix","OS Version*":"RHEL 7.9","Server environment*":"Non-production"},
"Server 3":{"OS Type*":"Windows","OS Version*":"Windows Server 2019","Server environment*":"Non-production"}}

The result is not exactly the same, but close.结果并不完全相同,但很接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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