2016-11-11 20 views
0

我有一個csv文件。列x具有字符串值。根據列x中的值,我想在其他csv中填充其他列。我怎麼做?我想要讀取csv文件中的列x並根據列x中的內容填充其他列?我如何在Python中做到這一點?

+0

你嘗試過什麼,嘗試更加具體,給您的數據和預期輸出的例子。並查看[Pandas](http://pandas.pydata.org/)庫 –

+0

提及您的輸入和所需的輸出。 「 – Chandan

+0

」在不同的csv中「意味着你有另一個你想要更新的預先存在的文件,或者你想創建一個基於第一個文件的新文件? – gboffi

回答

0

如果傳遞給函數的行號的列號

def readCSVfile(line, column): 
    fp = open("file") 
    for i, line in enumerate(fp): 
     if i == line-1: 
      res = line.split(',') 
    fp.close() 
    return res[column] 
0

我的回答解決處理您的數據 的一列,並寫入新的問題,您也許能夠做這樣的事文件來保存處理結果。

下面的代碼有內聯評論,我希望它能闡明它的內部。

# processing csv files is simple 
# but there are lots of details that can go wrong, 
# let's use a builtin module 
import csv 

# to abstract your (underspecified) problem, let's assume that 
# we have defined what we want to do to our data in terms 
# of a set of functions 
from my_module import f0, f1, f2, ..., fn 

# let's define a bunch of constants, in real life these should rather be 
# command line arguments 
input = './a/path/name.csv'a 
out = './anothe/r_path/name.csv' 
index_x = 5 

# slurp in the data 
with f as open(input): 
    data = [row for row in csv.reader(f)] 

# transpose the data — list(...) is necessary for python 3 
# where zip() returns a generator 
data = list(zip(*data)) 

# extract the data 
x = data[index_x] 

# the data processing is done with a double loop, 
# the outer loop on x values, 
# the inner loop on the processing units (aka the imported functions) 
processed = [[f(item)] for item in x for f in [f0, f1, f2, ..., fn]] 

# eventually, output the results of our computations to a different csv file 
# using the writerows() method that nicely iteratates on the rows of its 
# argument in our behalf 
with f as open(out, 'w'): 
    csv.writer(f).writerows(processed) 
相關問題