Python 使用Pandas将csv数据分组到json中
我以前从未使用过Pandas,我正在尝试从csv数据到json的非常简单的转换 我的csv数据的格式如下:Python 使用Pandas将csv数据分组到json中,python,json,pandas,csv,Python,Json,Pandas,Csv,我以前从未使用过Pandas,我正在尝试从csv数据到json的非常简单的转换 我的csv数据的格式如下: Category | Type | Parameter Name | Parameter Value ---------|------|----------------|---------------- Windows | W1 | Width | 900 Windows | W1 | Height | 900 Windows | W2
Category | Type | Parameter Name | Parameter Value
---------|------|----------------|----------------
Windows | W1 | Width | 900
Windows | W1 | Height | 900
Windows | W2 | Width | 1200
Windows | W2 | Height | 500
Doors | D1 | Width | 900
Doors | D1 | Height | 2100
Doors | D2 | Width | 820
Doors | D2 | Height | 2100
我想制作这样的东西:
{
"Windows": {
"W1": {
"Height": 900,
"Width": 900
},
"W2": {
"Height": 500,
"Width": 1200
},
},
"Doors: {
"D1": {
"Height": 2100,
"Width": 900
},
"D2": {
"Height": 2100,
"Width": 500
},
},
}
有人能帮忙吗?没有时间做更多的事情。希望这有帮助
s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]]
def redict(s):
if s.index.nlevels == 1:
return s.to_dict()
else:
return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)}
redict(s)
{'Doors': {'D1': {'Height': 2100, 'Width': 900},
'D2': {'Height': 2100, 'Width': 820}},
'Windows': {'W1': {'Height': 900, 'Width': 900},
'W2': {'Height': 500, 'Width': 1200}}}
稍微修改一下,我们就得到了
json
s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]]
def redict(s):
if s.index.nlevels == 1:
return s.astype(str).to_dict()
else:
return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)}
json.dumps(redict(s))
'{"Doors": {"D1": {"Width": "900", "Height": "2100"}, "D2": {"Width": "820", "Height": "2100"}}, "Windows": {"W1": {"Width": "900", "Height": "900"}, "W2": {"Width": "1200", "Height": "500"}}}'
没有时间做更多。希望这有帮助
s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]]
def redict(s):
if s.index.nlevels == 1:
return s.to_dict()
else:
return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)}
redict(s)
{'Doors': {'D1': {'Height': 2100, 'Width': 900},
'D2': {'Height': 2100, 'Width': 820}},
'Windows': {'W1': {'Height': 900, 'Width': 900},
'W2': {'Height': 500, 'Width': 1200}}}
稍微修改一下,我们就得到了
json
s = df.set_index(df.columns[:-1].tolist())[df.columns[-1]]
def redict(s):
if s.index.nlevels == 1:
return s.astype(str).to_dict()
else:
return {k: redict(g.xs(k)) for k, g in s.groupby(level=0)}
json.dumps(redict(s))
'{"Doors": {"D1": {"Width": "900", "Height": "2100"}, "D2": {"Width": "820", "Height": "2100"}}, "Windows": {"W1": {"Width": "900", "Height": "900"}, "W2": {"Width": "1200", "Height": "500"}}}'
Pandas DataFrame的函数为read_csv()和to_json()。是的,我可以将csv转换为DataFrame,但不确定如何将其分组为嵌套格式Pandas DataFrame的函数为read_csv()和to_json()。是的,我可以将csv转换为DataFrame,但不确定如何将其分组为嵌套格式