Search code examples
pythonpython-3.xcsvpython-3.7opencsv

Mapping row values of one CSV to the header values of another CSV and writing a new CSV file in Python


import numpy as np
import pandas as pd
import csv

data=np.loadtxt(open("ff.csv","rb"),delimiter=",",dtype=np.str)
print(data)

data1=np.loadtxt(open("x.csv","rb"),delimiter=",",dtype=np.str)
print(data1)

for i in range(1,len(data)):
    
    for j in range(len(data1[0])):
        
        if data[i] == data1[0][j]:
            print(data[i],",",data1[0][j])
        
            column = pd.read_csv("x.csv",usecols=[data1[0][j]])
            print(column)

This is first csv data name is in row

here data is in columns

I want to match row name with column name and save it into new csv according to match with row

output what I want here


Solution

  • Pandas is a useful tool here - you can pull your column names into a list, pass that list to your second sheet of data as a subset of columns to pull, and then save that dataframe to a new file.

    data=pd.read_csv("ff.csv", header = 0)
    
    data1=pd.read_csv("x.csv", header = 0)
    
    column_list = data['Name'].to_list()
    column_list.append('class')
    
    data1[column_list].to_csv("newfile.csv",index=False)