使用python读取/写入/附加到CSV
我正在尝试使用python的CSV模块修改CSV文件。该文件表示股票,并以列的形式列出当天的日期、开盘价、高价、低价、收盘价和成交量。我想做的是通过对现有数据执行代数来创建多个新列。例如,我想在这里创建一个列,显示任意一天开盘价与高价之间的百分比,以及从昨天收盘价到今天收盘价之间的百分比变化,现在考虑添加10个列 有没有一种紧凑的方法可以做到这一点?现在,我正在打开原始文件,并将感兴趣的值读取到列表中。然后使用该列表将修改后的值写入某个临时文件。然后使用for循环写入新文件,并添加每个电子表格中的行。然后将新文件的全部内容写入原始csv,因为我想保留csv ticker.csv的名称 希望我已经把我的问题说清楚了。如果您想要任何澄清或进一步的细节,请不要犹豫 编辑:我已经包含了下面一个函数的代码片段。该函数试图创建一个新列,该列包含从昨天收盘到今天收盘的百分比变化使用python读取/写入/附加到CSV,python,csv,Python,Csv,我正在尝试使用python的CSV模块修改CSV文件。该文件表示股票,并以列的形式列出当天的日期、开盘价、高价、低价、收盘价和成交量。我想做的是通过对现有数据执行代数来创建多个新列。例如,我想在这里创建一个列,显示任意一天开盘价与高价之间的百分比,以及从昨天收盘价到今天收盘价之间的百分比变化,现在考虑添加10个列 有没有一种紧凑的方法可以做到这一点?现在,我正在打开原始文件,并将感兴趣的值读取到列表中。然后使用该列表将修改后的值写入某个临时文件。然后使用for循环写入新文件,并添加每个电子表格中
def add_col_pchange(ticker):
"""
Add column with percent change in closing price.
"""
original = open('file1', 'rb')
reader = csv.reader(original)
reader.next()
close = list()
for row in reader:
# build list of close values; entries from left to right are reverse chronological
# index 4 corresponds to "Close" column
close.append(float(row[4])
original.close()
new = open(file2, 'wb')
writer = csv.writer(new)
writer.writerow(["Percent Change"])
pchange = list()
for i in (0, len(close)-1):
x = (close[i]-close[i+1])/close[i+1]
pchange.append(x)
new.close()
# open original and new csv's as read, write out to some new file.
# later, copy that entire file to original csv in order to maintain
# original csv's name and include new data
希望这有帮助
def add_col_pchange(ticker):
"""
Add column with percent change in closing price.
"""
# always use with to transparently manage opening/closing files
with open('ticker.csv', 'rb') as original:
spam = csv.reader(original)
headers = spam.next() # get header row
# get all of the data at one time, then transpose it using zip
data = zip(*[row for row in spam])
# build list of close values; entries from left to right are reverse chronological
# index 4 corresponds to "Close" column
close = data[4] # the 5th column has close values
# use map to process whole column at one time
f_pchange = lambda close0, close1: 100 * (float(close0) - float(close1)) / float(close1)
Ndays = len(close) # length of table
pchange = map(f_pchange, close[:-1], close[1:]) # list of percent changes
pchange = (None,) + tuple(pchange) # add something for the first or last day
headers.append("Percent Change") # add column name to headers
data.append(pchange)
data = zip(*data) # transpose back to rows
with open('ticker.csv', 'wb') as new:
spam = csv.writer(new)
spam.writerow(headers) # write headers
for row in data:
spam.writerow(row)
# open original and new csv's as read, write out to some new file.
# later, copy that entire file to original csv in order to maintain
# original csv's name and include new data
你也应该退房;你可以使用loadtxt和向量数学,但@lightalchesman是对的,它就是为此而设计的。唉,至少我不清楚。然而,我想你只需要通过一次就可以把数据读入内存,再通过另一次就可以把它写出来——我怀疑中间文件是否真的有必要。为了提供更清晰的解释,请至少发布代码的概要。@LarryLustig-edit。谢谢你的回复!你可能想考虑使用熊猫图书馆。您可以将csv文件作为数据帧读入,创建一个新系列,并在写入之前将该系列附加到数据帧。