buckenup
buckenup

Reputation: 49

How to append to the bottom row of two columns of a csv file using pandas?

I have a function that basically returns the date today and a random integer to the bottom of their respective columns each time the function is called.

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)

For the first two time the function is called it works as expected and returns this in the csv file:

Date,Price
2021-06-26,29
2021-06-26,97

However calling the function afterwards returns an error: 'ValueError: Length of values (1) does not match length of index (2)'

I plan to call the function for a n number of consecutive days on the same csv file.

Upvotes: 0

Views: 279

Answers (2)

tiggyliv
tiggyliv

Reputation: 71

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)

Upvotes: 1

nay
nay

Reputation: 1775

as Rob Raymond said.you today list and random list is not match you csv length.so you should make them match.and every time you write to_csv.the mode is a which is append new row to it.

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)

only append new row after each run

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)])

Upvotes: 0

Related Questions