Split (explode) pandas dataframe string entry to separate rows

后端 未结 22 3491
一向
一向 2020-11-21 05:03

I have a pandas dataframe in which one column of text strings contains comma-separated values. I want to split each CSV field and create a new row per entry (as

22条回答
  •  情书的邮戳
    2020-11-21 05:26

    Another solution that uses python copy package

    import copy
    new_observations = list()
    def pandas_explode(df, column_to_explode):
        new_observations = list()
        for row in df.to_dict(orient='records'):
            explode_values = row[column_to_explode]
            del row[column_to_explode]
            if type(explode_values) is list or type(explode_values) is tuple:
                for explode_value in explode_values:
                    new_observation = copy.deepcopy(row)
                    new_observation[column_to_explode] = explode_value
                    new_observations.append(new_observation) 
            else:
                new_observation = copy.deepcopy(row)
                new_observation[column_to_explode] = explode_values
                new_observations.append(new_observation) 
        return_df = pd.DataFrame(new_observations)
        return return_df
    
    df = pandas_explode(df, column_name)
    

提交回复
热议问题