[英]I want to read a column x in a csv file and populate other columns based on the content in the column x ? How do i do that in Python?
I have a csv file. 我有一个csv文件。 A column x has string values.
x列具有字符串值。 Based on the values in the column x , I want to populate other columns in a different csv.
基于x列中的值,我想在其他csv中填充其他列。 how do I do that?
我怎么做?
you might be able to do something like this if you pass to the function a line number an a column number 如果将函数的行号和列号传递给函数,则可能可以执行以下操作
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]
My answer addresses the problem of processing a column of your data and writing a NEW file to save the results of processing. 我的答案解决了处理您的一列数据并编写新文件以保存处理结果的问题。
The following code has inline comments that, I hope, will clarify its innards. 我希望以下代码具有内联注释,以阐明其内在含义。
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.