티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Pandas DataFrame to List of Dictionaries

판다스(Pandas) 데이터프레임(DataFrame)을 딕셔너리의 리스트로 변환하기

 문제 내용 

I have the following DataFrame:

다음과 같은 데이터 프레임이 있습니다:
 customer    item1      item2    item3 1           apple      milk     tomato 2           water      orange   potato 3           juice      mango    chips 

 

which I want to translate it to list of dictionaries per row

행별로 딕셔너리의 리스트로 변환하려면 다음과 같이 합니다.
rows = [
    {
        'customer': 1,
        'item1': 'apple',
        'item2': 'milk',
        'item3': 'tomato'
    }, {
        'customer': 2,
        'item1':
        'water',
        'item2': 'orange',
        'item3': 'potato'
    }, {
        'customer': 3,
        'item1': 'juice',
        'item2': 'mango',
        'item3': 'chips'
    }
]

 

 

 높은 점수를 받은 Solution 

Use df.to_dict('records') -- gives the output without having to transpose externally.

df.to_dict('records') -- 데이터프레임을 전치(transpose)할 필요 없이 출력합니다.
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2L, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3L, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

 

 

 가장 최근 달린 Solution 

If you are interested in only selecting one column this will work.

만약 하나의 열(column)만 선택하고자 한다면 다음과 같이 합니다.
df[["item1"]].to_dict("records")

 

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

아래 코드는 동작하지 않습니다. TypeError: unsupported type: 가 발생하는데, 이는 시리즈(Series)를 딕셔너리로 변환하려고 시도하였기 때문으로 추정됩니다.
df["item1"].to_dict("records")

 

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

저는 하나의 열(column)만 선택하여 열 이름을 키(key)로 하는 딕셔너리의 리스트로 변환해야 하는 요구사항이 있었고, 이 문제에서 조금 막혀서 해결 방법을 공유하려고 합니다.

 

 

 

출처 : https://stackoverflow.com/questions/29815129/pandas-dataframe-to-list-of-dictionaries

반응형
댓글
공지사항
최근에 올라온 글