Home > other >  Populating script results into CSV file in correct format using pandas
Populating script results into CSV file in correct format using pandas

Time:10-05

Excuse rookie errors, I'm pretty new to Python and even newer to using pandas.

The script so far counts the rows of below csv file (generated by a different script) and that value is stored as totalDailyListings correctly. There is some formatting with the date as I want to get to a point whereby this script counts the day befores listings.

The current structure of CSV file that rows are being counted from:

Address Price
123 Main St £305,000
55 Chance Way £200,000
from datetime import date, timedelta

oneday = timedelta(days=1)
yesterdayDate = date.today() - oneday
filename = 'ballymena-'   str(yesterdayDate)   '.csv'

results = pd.read_csv(filename)
totalDailyListings = (len(results))
# calculates the correct number of rows in csv

listings = pd.DataFrame(
    [yesterdayDate, totalDailyListings], columns=['Date', 'Total'])
listings.to_csv('listings-count.csv')

I'm struggling however to create a new CSV file with just two columns: "Date" and "Total" and that would allow that CSV file to be updated (rows added) daily for long term monitoring. Can anyone offer some tips to point me back in the right direction?

Desired CSV format:

Date Total
2022-10-04 305
2022-10-05 200

CodePudding user response:

The important part is the structure of the resulting dataframe

df = pd.DataFrame({'Date':['2022-10-04', '2022-10-05'], 'Total': [305, 200]})
df.to_csv('listing-count-default_index.csv')
df.set_index('Date', inplace=True)
df.to_csv('listing-count.csv')

This should give you just two columns

  • Related