JSON을 Pandas 데이터 프레임으로 구문 분석하는 동안 부모를 제거하는 방법은 무엇입니까?

Sreyan Ghosh

다음 API 응답의 데이터를 pandas 데이터 프레임으로 구문 분석하고 싶습니다. 이 JSON 파일에는 문제를 일으키는 추가 부모가 있습니다. 이것을 제거하고 데이터를 올바르게 구문 분석하려면 어떻게해야합니까?

URL : "https://api.covid19india.org/state_district_wise.json"

    import pandas as pd
    URL = "https://api.covid19india.org/state_district_wise.json"
    df = pd.read_json(URL)
    df.head()

위의 코드는 작동하지 않고 잘못된 출력을 제공합니다. 도와주세요.

이스 르엘

파이썬에서 중첩 구조를 구문 분석하는 것은 고통 스럽습니다. 여기에 데이터에 대한 솔루션이 있습니다.

import requests

URL = "https://api.covid19india.org/state_district_wise.json"
d = requests.get(URL).json()


L = []
for k, v in d.items():
    for k1, v1 in v.items():
        if isinstance(v1, dict):
            for k2, v2 in v1.items():
                if isinstance(v2, dict):
                    for k3, v3 in v2.items():
                        if isinstance(v3, dict):
                            d1 = {f'{k3}.{k4}': v4 for k4, v4 in v3.items()}
                            d2 = {'districtData':k,'State':k2,'statecode': v['statecode']}
                            d3 = {**d2, **v2, **d1}
                            del d3[k3]
                            L.append(d3)

df = pd.DataFrame(L)

print (df)

                    districtData                     State statecode  \
0               State Unassigned                Unassigned        UN   
1    Andaman and Nicobar Islands                  Nicobars        AN   
2    Andaman and Nicobar Islands  North and Middle Andaman        AN   
3    Andaman and Nicobar Islands             South Andaman        AN   
4    Andaman and Nicobar Islands                   Unknown        AN   
..                           ...                       ...       ...   
767                  West Bengal           Purba Bardhaman        WB   
768                  West Bengal           Purba Medinipur        WB   
769                  West Bengal                   Purulia        WB   
770                  West Bengal         South 24 Parganas        WB   
771                  West Bengal            Uttar Dinajpur        WB   

                                                 notes  active  confirmed  \
0                                                            0          0   
1    District-wise numbers are out-dated as cumulat...       0          0   
2    District-wise numbers are out-dated as cumulat...       0          1   
3    District-wise numbers are out-dated as cumulat...      19         51   
4                                                          148       4442   
..                                                 ...     ...        ...   
767                                                        618       8773   
768                                                       1424      16548   
769                                                        350       5609   
770                                                       1899      27445   
771                                                        358       5197   

     deceased  recovered  delta.confirmed  delta.deceased  delta.recovered  
0           0          0                0               0                0  
1           0          0                0               0                0  
2           0          1                0               0                0  
3           0         32                0               0                0  
4          60       4234                0               0                0  
..        ...        ...              ...             ...              ...  
767        74       8081                0               0                0  
768       212      14912                0               0                0  
769        33       5226                0               0                0  
770       501      25045                0               0                0  
771        55       4784                0               0                0  

[772 rows x 11 columns]

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관