How to split/expand a string value into several pandas DataFrame rows?

前端 未结 3 1529
盖世英雄少女心
盖世英雄少女心 2020-11-27 22:30

Let\'s say my DataFrame df is created like this:

df = pd.DataFrame({\"title\" : [\"Robin Hood\", \"Madagaskar\"],
                  \"genres\" :         


        
3条回答
  •  天涯浪人
    2020-11-27 23:01

    Since pandas >= 0.25.0 we have a native method for this called explode.

    This method unnests each element in a list to a new row and repeats the other columns.

    So first we have to call Series.str.split on our string value to split the string to list of elements.

    >>> df.assign(genres=df['genres'].str.split(', ')).explode('genres')
    
            title     genres
    0  Robin Hood     Action
    0  Robin Hood  Adventure
    1  Madagaskar     Family
    1  Madagaskar  Animation
    1  Madagaskar     Comedy
    

提交回复
热议问题