Splitting dictionary/list inside a Pandas Column into Separate Columns

后端 未结 12 1452
南方客
南方客 2020-11-22 02:50

I have data saved in a postgreSQL database. I am querying this data using Python2.7 and turning it into a Pandas DataFrame. However, the last column of this dat

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:30

    I've concatenated those steps in a method, you have to pass only the dataframe and the column which contains the dict to expand:

    def expand_dataframe(dw: pd.DataFrame, column_to_expand: str) -> pd.DataFrame:
        """
        dw: DataFrame with some column which contain a dict to expand
            in columns
        column_to_expand: String with column name of dw
        """
        import pandas as pd
    
        def convert_to_dict(sequence: str) -> Dict:
            import json
            s = sequence
            json_acceptable_string = s.replace("'", "\"")
            d = json.loads(json_acceptable_string)
            return d    
    
        expanded_dataframe = pd.concat([dw.drop([column_to_expand], axis=1),
                                        dw[column_to_expand]
                                        .apply(convert_to_dict)
                                        .apply(pd.Series)],
                                        axis=1)
        return expanded_dataframe
    

提交回复
热议问题