다음과 같은 데이터 프레임이 있습니다.
Lvl1 lvl2 lvl3 lvl4 lvl5
x 1x 3xx 1 "text1"
x 1x 3xx 2 "text2"
x 1x 3xx 3 "text3"
x 1x 4xx 4 "text4"
x 2x 4xx 5 "text5"
x 2x 4xx 6 "text6"
y 2x 5xx 7 "text7"
y 3x 5xx 8 "text8"
y 3x 5xx 9 "text9"
y 3x 6xx 10 "text10"
y 4x 7xx 11 "text11"
y 4x 7xx 62 "text12"
y 4x 8xx 62 "text13"
z
z
z
w
w
w
I would like to convert to nested json so it looks like this:
[{
"x":{
"1x":[{
"3xx": [
{
lvl4: 1
lvl5: "text1"
},
{
lvl4: 2
lvl5: "text2"
},
{
lvl4: 3
lvl5: "text3"
}],
"4xx": [
{
lvl4: 4
lvl5: "text4"
}],
"2x":[{
"4xx": [
{
lvl4: 5
lvl5: "text5"
},
{
lvl4: 6
lvl5: "text6"
}],
"5xx": [
{
lvl4: 7
lvl5: "text7"
}],
}]
. . .
여기 에서 예제를 시작으로 사용하고 있지만 표시된 데이터에서와 같이 들여 쓰기 된 lvl1, lvl2, lvl3이 필요합니다. 참조 예제는 동일한 수준에서 lvl1, lvl2, lvl3을 반환합니다.
또한 lvl 값이되도록 lvl의 키가 필요합니다. 예 : "lvl1"이 아닌 "x".
[{
"x":{
감사합니다
예상 출력에 따라 세 개의 중첩 groupby
및 to_dict
. 더 나은 방법이 있지만 적어도 시작은 가능합니다.
[df.groupby('Lvl1')\
.apply(lambda x: x.groupby('lvl2')\
.apply(lambda x: [x.groupby('lvl3')
.apply(lambda x: x[['lvl4','lvl5']].to_dict('r')
).to_dict()]
).to_dict()
).to_dict()]
[{'x': {'1x': [{'3xx': [{'lvl4': 1, 'lvl5': '"text1"'},
{'lvl4': 2, 'lvl5': '"text2"'},
{'lvl4': 3, 'lvl5': '"text3"'}],
'4xx': [{'lvl4': 4, 'lvl5': '"text4"'}]
}],
'2x': [{'4xx': [{'lvl4': 5, 'lvl5': '"text5"'},
{'lvl4': 6, 'lvl5': '"text6"'}]}]},...
정확한 외부 형식에 의문이 있습니다.
@Trenton McKinney 덕분에 편집하면 다음과 같이 보입니다.
df['lvl5'] = df['lvl5'].str.strip('"')
test = [df.groupby('Lvl1')\
.apply(lambda x: x.groupby('lvl2')\
.apply(lambda x: [x.groupby('lvl3')
.apply(lambda x: x[['lvl4','lvl5']].to_dict('r')
).to_dict()]
).to_dict()
).to_dict()]
import json
json_res = list(map(json.dumps, test))
그런 다음 json_res
json 요구에 맞출 수 있습니다.
test
는 큰 따옴표로 묶인 json 형식으로 올바르게 저장 됩니다.with open('data.json', 'w') as f:
json.dump(test, f)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다