我有一个函数,每次调用该函数时,它基本上都会返回今天的日期,并在各自列的底部返回一个随机整数。
def date_to_csv():
import pandas as pd
from random import randint
df = pd.read_csv("test.csv")
df['Date'] = [datetime.date.today()]
df['Price'] = [randint(1,100)]
df.to_csv('test.csv',mode='a',index=False,header=None)
在前两次调用函数时,它按预期工作,并在csv文件中返回:
Date,Price
2021-06-26,29
2021-06-26,97
然而,随后调用该函数会返回一个错误:"ValueError:Length of values(1(not match Length of index(2(">
我计划在同一个csv文件上连续n天调用该函数。
try:
df = pd.read_csv("test.csv")
df = df.append({'Date':datetime.date.today(), 'Price':randint(1,100)})
df.to_csv('test.csv',mode='a',index=False,header=None)
正如Rob Raymond所说。您今天的列表和随机列表与您的csv长度不匹配。因此,您应该使它们匹配。每次写入csv时,模式为a
,即向其添加新行。
df = pd.read_csv("test.csv")
length = df.shape[0]
df['Date'] = [datetime.date.today() for _ in range(length)]
df['Price'] = [randint(1,100) for _ in range(length)]
df.to_csv('test.csv',mode='a',index=False,header=None)
每次运行后只追加新行
df = pd.read_csv("test.csv")
df = df.append({'Date':datetime.date.today(), 'Price':randint(1,100)},ignore_index=True)
df.to_csv('test.csv',mode='w',index=False)
df = pd.DataFrame({'Date':[datetime.date.today()], 'Price':[randint(1,100)]})
df.to_csv('test.csv',mode='a',index=False,header=None)
with open('test.csv','a') as f:
writer = csv.writer(f)
writer.writerow([datetime.date.today(),randint(1,100)])