csv가져와서 dict 파이썬

조회수 871회

제가 csv를 불러와서 사전안에 사전형태로 넣고 싶은데요. {test1:{testgroup3:{a:100, b:200, c:200}, testgroup2{a:100, b:1000, c:200}, testgroup{a:200, b:100, c:200}}, test2{testgroup3{a:200, b:100, c:200}}, testgroup2{a:200, b:100, c:200}}, testgroup{a:200, b:100, c:200}}}이런식으로 사전안에 사전 형식을 만들고 싶습니다.

import pandas as pd
df = pd.read_csv('csv.csv',sep=',')
dict1 = df.set_index('campaign').to_dict('list')
dict2 = df.to_dict(orient="index")

print(dict2)

여기 까지 하고나서 더이상 어떻게 해야할지 모르겠네요.


csv 파일은 다음과 같은 형식입니다.

campaign 그룹 a b c
test1 testgroup1 100 200 200

3 답변

  • 더 좋은방법이 있을거 같긴한데 to_dict 으로는 원하는대로 안되서..

    참고부탁드립니다.

    #test.csv
    #campaign,group,a,b,c
    #test1,testgroup1,101,201,301
    #test1,testgroup2,101,201,301
    #test2,testgroup1,102,202,302
    #test2,testgroup2,102,202,302
    #test2,testgroup3,102,202,302
    
    import pandas as pd
    
    def to_dict(df):
        tmp = ''
        sep1 = {}
    
        for idx, i in enumerate(df.iterrows()):
            if i[1][0] != tmp:
                tmp = i[1][0]
                sep2 = {}
            sep3 = i[1][2:].to_dict()
            sep2[i[1][1]] = sep3
            sep1[tmp] = sep2
        return sep1
    
    def main():
        df = pd.read_csv('test.csv', sep=',')
        r = to_dict(df)
        print(r['test1'])
        print(r['test2'])
        print(r)
    
    if __name__ == "__main__":
        main()
    
    #result
    #{'testgroup1': {'a': 101, 'b': 201, 'c': 301}, 'testgroup2': {'a': 101, 'b': 201, 'c': 301}}
    #{'testgroup1': {'a': 102, 'b': 202, 'c': 302}, 'testgroup2': {'a': 102, 'b': 202, 'c': 302}, 'testgroup3': {'a': 102, 'b': 202, 'c': 302}}
    #{'test1': {'testgroup1': {'a': 101, 'b': 201, 'c': 301}, 'testgroup2': {'a': 101, 'b': 201, 'c': 301}}, 'test2': {'testgroup1': {'a': 102, 'b': 202, 'c': 302}, 'testgroup2': {'a': 102, 'b': 202, 'c': 302}, 'testgroup3': {'a': 102, 'b': 202, 'c': 302}}}
    
    • testgroup1,testgroup2,testgroup3 을 test가 포함하고 test가 여러개 있다면 어떡해야 하는지 아시나요? 알 수 없는 사용자 2020.10.8 17:11
    • 뒤에 abc 말고 abcdefg.... 와도 정상적으로 됩니다 그리고 맨밑줄 다시 확인해주세요 일부 수정했습니다 김호원 2020.10.8 17:14
    • 네 정말로 감사합니다 !! 알 수 없는 사용자 2020.10.8 17:17
  • pd.DataFrame 의 to_dict 에 여러 재미있는 옵션이 있군요.

    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html

    >>> from io import StringIO
    >>> import pandas as pd
    >>> s = '''campaign 그룹 a b c
    test1 testgroup1 100 200 200
    test1 testgroup2 200 300 400
    test2 testgroup3 300 10 20'''
    >>> df = pd.read_csv(StringIO(s.replace(' ', ',')))
    >>> df
      campaign          그룹    a    b    c
    0    test1  testgroup1  100  200  200
    1    test1  testgroup2  200  300  400
    2    test2  testgroup3  300   10   20
    >>> dic = {}
    >>> for camp, g in df.groupby('campaign'):
        df2 = g.iloc[:,1:].set_index("그룹")
        dic[camp] = df2.to_dict('index')
    
    
    >>> dic
    {'test1': {'testgroup1': {'a': 100, 'b': 200, 'c': 200}, 'testgroup2': {'a': 200, 'b': 300, 'c': 400}}, 'test2': {'testgroup3': {'a': 300, 'b': 10, 'c': 20}}}
    >>> from pprint import pprint
    >>> pprint(dic)
    {'test1': {'testgroup1': {'a': 100, 'b': 200, 'c': 200},
               'testgroup2': {'a': 200, 'b': 300, 'c': 400}},
     'test2': {'testgroup3': {'a': 300, 'b': 10, 'c': 20}}}
    
    • :D groupby 이용하면 쉽게 해결됬던거네요 저도 배워갑니다 김호원 2020.10.8 17:26
    • 오 이런방법도 있었네요 많이 배워갑니다 ㅎㅎ 알 수 없는 사용자 2020.10.8 17:27
  • 이런방법도 있습니다.

    from io import StringIO
    s = StringIO('''campaign,group,a,b,c
    test1,testgroup1,101,201,301
    test1,testgroup2,101,201,301
    test2,testgroup1,102,202,302
    test2,testgroup2,102,202,302
    test2,testgroup3,102,202,302
    ''')
    
    df = pd.read_csv(s, sep=",")
    df.set_index(['campaign', 'group'], inplace=True)
    df.groupby(level=0).apply(lambda _df: _df.xs(_df.name).to_dict('index')).to_dict()
    
    {'test1': {'testgroup1': {'a': 101, 'b': 201, 'c': 301},
      'testgroup2': {'a': 101, 'b': 201, 'c': 301}},
     'test2': {'testgroup1': {'a': 102, 'b': 202, 'c': 302},
      'testgroup2': {'a': 102, 'b': 202, 'c': 302},
      'testgroup3': {'a': 102, 'b': 202, 'c': 302}}}
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)