将一个CSV的行值映射到另一个CSV的标题值并在python中写入新的CSV文件

问题描述 投票:0回答:1
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 coloums

要使行名与coloum名称匹配,并根据与行的匹配将其保存到新的csv中

output what I want here

python python-3.x csv python-3.7 opencsv
1个回答
0
投票

Pandas在这里是有用的工具-您可以将列名称拉入列表,将该列表作为要拉的列子集传递到第二个数据表,然后将该数据框保存到新文件中。

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)
© www.soinside.com 2019 - 2024. All rights reserved.