How to widen a dataframe - pandas

前端 未结 1 412
渐次进展
渐次进展 2021-01-14 09:58

Basically i want to just flatten ( maybe not good term )

for example having dataframe:

    A      B            C
0   1  [1,2]      [1, 10]
1   2  [2,         


        
相关标签:
1条回答
  • 2021-01-14 10:39

    General solution working also if lists have differents lengths:

    df1 = pd.DataFrame(df['B'].values.tolist())
    df2 = pd.DataFrame(df['C'].values.tolist())
    
    df = pd.concat([df[['A']], df1, df2], axis=1)
    df.columns = [df.columns[0]] + [f'B{i+1}' for i in range(len(df.columns)-1)]
    print (df)
       A  B1  B2  B3  B4
    0  1   1   2   1  10
    1  2   2  14   2  18
    

    If same size:

    df1 = pd.DataFrame(np.array(df[['B','C']].values.tolist()).reshape(len(df),-1))
    df1.columns = [f'B{i+1}' for i in range(len(df1.columns))]
    df1.insert(0, 'A', df['A'])
    print (df1)
       A  B1  B2  B3  B4
    0  1   1   2   1  10
    1  2   2  14   2  18
    
    0 讨论(0)
提交回复
热议问题