split rows in pandas dataframe

后端 未结 4 770
無奈伤痛
無奈伤痛 2021-01-05 16:17

i stuck with the problem how to devide pandas dataframe by row,

i have similar dataframe with column where values separated by \\r\\n and they are in one cell,

4条回答
  •  情深已故
    2021-01-05 16:39

    As commented, str.split() followed by explode is helpful. If you are not on Pandas 0.25, then you can use melt afterward:

    (pd.concat( (df.Shape.str.split('\r\n', expand=True), 
                df[['Color','Price']]),
              axis=1)
       .melt(id_vars=['Color', 'Price'], value_name='Shape')
       .dropna()
    )
    

    Output:

       Color  Price variable      Shape
    0  Green     10        0  Rectangle
    1   Blue     15        0  Rectangle
    2  Green     10        1   Triangle
    3   Blue     15        1   Triangle
    4  Green     10        2   Octangle
    

提交回复
热议问题