I have some code that takes a bunch of csv files and makes individual plots using the data. I was able to get help on the code (see here: Automate making multiple plots in python using several .csv files) but now I want to alter it such that wherever the code says name
will be replaced with the name of the file in the files
vector. For some reasons this works in the final line of code plt.savefig('{}.png'.format(fn))
but nowhere else.
import pandas as pd
from dateutil import parser, rrule
from datetime import datetime, time, date
import time
import os
import matplotlib.pyplot as plt
files = ['a.pd.csv',
't.pd.csv',
'r.pd.csv',
'n.pd.csv',
'm.pd.csv',
'k.pod.csv']
for f in files:
fn = f.split('.')[0]
dat = pd.read_csv(f)
df0 = dat.loc[:, ['TimeStamp', 'RF']]
# Change time format
df0["time"] = pd.to_datetime(df0["TimeStamp"])
df0["day"] = df0['time'].map(lambda x: x.day)
df0["month"] = df0['time'].map(lambda x: x.month)
df0["year"] = df0['time'].map(lambda x: x.year)
df0.to_csv("name_1.csv", na_rep="0") # write to csv
# Combine for daily rainfall
df1 = pd.read_csv('name_1.csv', encoding='latin-1',
usecols=['day', 'month', 'year', 'RF', 'TimeStamp'])
df2 = df1.groupby(['day', 'month', 'year'], as_index=False).sum()
df2.to_csv("name_2.csv", na_rep="0", header=None) # write to csv
# parse date
df3 = pd.read_csv("name_2.csv", header=None, index_col='datetime',
parse_dates={'datetime': [1,2,3]},
date_parser=lambda x: pd.datetime.strptime(x, '%d %m %Y'))
def dt_parse(date_string):
dt = pd.datetime.strptime(date_string, '%d %m %Y')
return dt
# sort datetime
df4 = df3.sort()
final = df4.reset_index()
# rename columns
final.columns = ['date', 'bleh', 'rf']
final[['date','rf']].plot()
plt.suptitle('Name Rain 2015-2016', fontsize=20) #changename
plt.xlabel('DOY', fontsize=18)
plt.ylabel('Rain / mm', fontsize=16)
plt.savefig('{}.png'.format(fn))