Home > Back-end >  Converting 3 Columns into 2 Column - Python
Converting 3 Columns into 2 Column - Python

Time:11-18

I need to convert 3 columns into 2 rows using python.  
   col1 col2 col3  
    A      2    3  
    B      4    5  
    
    col1  col2  
    A      2  
    A      3  
    B      4  
    B      5  

*my code hdr = ['col1', 'col2'] final_output=[] for row in rows: output = {} output1 = {} output = { A : row.get(col1), B: row.get(col2)} output1 = { A : row.get(col1), B: row.get(col3)}

final_out.append(output)
final_out.append(output1)

with open(tgt_file.csv, w) as tgt_file:
    csv_writer=csv.DictWriter(tgt_file, fieldnames=hdr, delimiter=',')
    csv_writer.writeheader()
    csv_writer.writerows(final_output)

CodePudding user response:

import pandas as pd
### this is the sample data
df = pd.DataFrame(data= [['A',2, 3],['B',4, 5]], 
              columns =['col1', 'col2', 'col3'])

### this is the solution
ef = []            # create an empty list
for i,row in df.iterrows():
    ef.append([row[0], row[1]])   # append first column first
    ef.append([row[0], row[2]])   # append 2nd column second

df = pd.DataFrame(data=ef,columns=['col1','col2']) # recreate the dataframe

remark: there are more advanced solutions possible, but I think this is readable

CodePudding user response:

You can try using pd.melt

df = pd.melt(df, id_vars=["col1"],value_name = 'col2').drop(['variable'],axis=1)

And then you can sort the dataframe on "col1".

  • Related