Split (explode) pandas dataframe string entry to separate rows

后端 未结 22 3504
一向
一向 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:15

    Upon adding few bits and pieces from all the solutions on this page, I was able to get something like this(for someone who need to use it right away). parameters to the function are df(input dataframe) and key(column that has delimiter separated string). Just replace with your delimiter if that is different to semicolon ";".

    def split_df_rows_for_semicolon_separated_key(key, df):
        df=df.set_index(df.columns.drop(key,1).tolist())[key].str.split(';', expand=True).stack().reset_index().rename(columns={0:key}).loc[:, df.columns]
        df=df[df[key] != '']
        return df
    

提交回复
热议问题