Lengthening a DataFrame based on stacking columns within it in Pandas

后端 未结 3 1715
走了就别回头了
走了就别回头了 2021-01-23 04:30

I am looking for a function that achieves the following. It is best shown in an example. Consider:

pd.DataFrame([ [1, 2, 3 ], [4, 5, np.nan ]], columns=[\'x\', \         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 05:24

    You can use stack to get things done i.e

    pd.DataFrame(df.set_index('x').stack().reset_index(level=0).values,columns=['x','y'])
    
         x    y
    0  1.0  2.0
    1  1.0  3.0
    2  4.0  5.0
    

提交回复
热议问题