Dictionary column in pandas dataframe

后端 未结 3 1824
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 00:51

I\'ve got a csv that I\'m reading into a pandas dataframe. However one of the columns is in the form of a dictionary. Here is an example:

ColA, ColB, ColC, C         


        
3条回答
  •  借酒劲吻你
    2020-12-24 01:09

    So starting with your one row df

        Col A   Col B   Col C                           Col D
    0   20      30      {u'we': 2, u'ab': 1, u'as': 3}  String1
    

    EDIT: based on the comment by the OP, I'm assuming we need to convert the string first

    import ast
    df["ColC"] =  df["ColC"].map(lambda d : ast.literal_eval(d))
    

    then we convert Col C to a dict, transpose it and then join it to the original df

    dfNew = df.join(pd.DataFrame(df["Col C"].to_dict()).T)
    dfNew
    

    which gives you this

        Col A   Col B   Col C                           Col D   ab  as  we
    0   20      30      {u'we': 2, u'ab': 1, u'as': 3}  String1 1   3   2
    

    Then we just select the columns we want in dfNew

    dfNew[["Col A", "Col B", "ab", "we", "as", "Col D"]]
    
        Col A   Col B   ab  we  as  Col D
    0   20      30      1   2   3   String1
    

提交回复
热议问题