Split (explode) pandas dataframe string entry to separate rows

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

    There are a lot of answers here but I'm surprised no one has mentioned the built in pandas explode function. Check out the link below: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.explode.html#pandas.DataFrame.explode

    For some reason I was unable to access that function, so I used the below code:

    import pandas_explode
    pandas_explode.patch()
    df_zlp_people_cnt3 = df_zlp_people_cnt2.explode('people')
    

    Above is a sample of my data. As you can see the people column had series of people, and I was trying to explode it. The code I have given works for list type data. So try to get your comma separated text data into list format. Also since my code uses built in functions, it is much faster than custom/apply functions.

    Note: You may need to install pandas_explode with pip.

提交回复
热议问题