2017-07-18 30 views
1

我試圖取代使用其中列名以普通ID給定的指標CSV文件,CSV文件的列名替換的單詞。我需要用id替換列名。如何找到並從2個CSV文件

例如,密鑰文件是這樣

ids colnames 
1 col1 val1 
2 col2 val2 
3 col3 val3 
4 col4 val5 
5 col5 val4 

而且我的價值觀文件是有點像這個

val1 val2 val3 val4 val5 
a 2 2 2 2 
b 3 3 3 3 
c 4 4 4 4 
d 5 5 5 5 
e 6 6 6 6 
f 7 7 7 7 
g 8 8 8 8 

但我需要輸出有點像這個

col1 col2 col3 col4 col5 
    a 2 2 2 2 
    b 3 3 3 3 
    c 4 4 4 4 
    d 5 5 5 5 
    e 6 6 6 6 
    f 7 7 7 7 
    g 8 8 8 8 

我寫了一個代碼來做到這一點,但我無法替換列名。請幫忙。

import csv, os 
import pandas as pd 

file1 = pd.read_csv("trial.csv", delimiter=",") 
file2 = pd.read_csv("try.csv", delimiter=",") 
out_csv = r"trialop.csv" 
tempFile = open("fileop", 'w+') 

header1 = file1.columns 
header2 = file2.columns 

content = file1.ids 
proid = file1.colnames 

for ids in content: 
    if ids in header2: 
     tempFile.write(header2.replace(header2, ids)) 

如果輸出文件本身可以是csv文件,它會更有幫助。

回答

0

此代碼應工作。

with open('trial.csv.txt','r') as file: 
    trial_raw = file.read() 
trial = trial_raw.split('\n') 
del trial[0] 

new_columns = [] 
for col in trial: 
    col1= col.split(',') 
    new_columns.append(col1[0]) 


with open('try.csv.txt','r') as file: 
    try_raw = file.read() 
try1 = try_raw.split('\n') 
del try1[0] 

new_columns_str= '' 

for cols in new_columns: 
    if new_columns.index(cols)!=len(new_columns)-1: 
     new_columns_str+=cols+',' 
    else: 
     new_columns_str+=cols 

#Inserts the new columns 
try1.insert(0,new_columns_str) 

new_file = '' 

for line in try1: 
    if try1.index(line)!=len(try1)-1: 
     new_file+=line+'\n' 
    else: 
     new_file+=line 
with open('trialop.csv','w')as file: 
    file.write(new_file) 
+0

我試過了,但我最終得到了列名編號,而不是我想要的方式。而且我的實際數據文件是500MB +,所以我不能依賴這個,因爲它會消耗大量的內存。任何其他更好和有效的方法?也許使用熊貓?謝謝 –