Python - Unnest cells in Pandas DataFrame

后端 未结 2 473
执念已碎
执念已碎 2021-01-12 07:14

Suppose I have DataFrame df:

a b c
v f 3|4|5
v 2 6
v f 4|5

I\'d like to produce this df:

<         


        
2条回答
  •  梦毁少年i
    2021-01-12 07:37

    You could:

    import numpy as np
    
    df = df.set_index(['a', 'b'])
    df = df.astype(str) + '| ' # There's a space ' ' to match the replace later
    df = df.c.str.split('|', expand=True).stack().reset_index(-1, drop=True).replace(' ', np.nan).dropna().reset_index() # and replace also has a space ' '
    

    to get:

       a  b  0
    0  v  f  3
    1  v  f  4
    2  v  f  5
    3  v  2  6
    4  v  f  4
    5  v  f  5
    

提交回复
热议问题