使用几个.csv文件在python中自动制作多个图 [英] Automate making multiple plots in python using several .csv files

查看:390
本文介绍了使用几个.csv文件在python中自动制作多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有14个.csv文件(每个位置一个.csv文件),用于制作每日降雨量14巴的地块。下面的代码是一个条形图的样子。

I have 14 .csv files (1 .csv file per location) that will be used to make a 14 bar plots of daily rainfall. The following code is an example of what one bar plot will look like.

import numpy as np
import pandas as pd 
from datetime import datetime, time, date
import matplotlib.pyplot as plt

# Import data
dat = pd.read_csv('a.csv')
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("a2.csv", na_rep="0")  # write to csv

# Combine for daily rainfall
df1 = pd.read_csv('a2.csv', encoding='latin-1',
              usecols=['day', 'month', 'year', 'RF', 'TimeStamp'])
df2 = df1.groupby(['day', 'month', 'year'], as_index=False).sum()
df2.to_csv("a3.csv", na_rep="0", header=None)  # write to csv

# parse date
df3 = pd.read_csv("a3.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('Rain 2015-2016', fontsize=20)
plt.xlabel('Date', fontsize=18)
plt.ylabel('Rain / mm', fontsize=16)
plt.savefig('a.jpg')
plt.show()

看起来像这样:

And the final plot looks like this:

如何自动化此代码写一个for循环可能吗?),这样我不必重新键入每个.csv文件的代码?这将是很好,如果代码也保存.csv的名称作为.jpg文件的名称的数字。

How can I automate this code (i.e. write a for-loop perhaps?) so that I don't have to re-type the code for each .csv file? It would be nice if the code also saves the figure with the name of the .csv as the name of the .jpg file.

这14个文件的名称如下:
names = [a.csv,b.csv,c.csv d.csv,e.csv,f.csv...]

The names of the 14 files are as such: names = ["a.csv","b.csv", "c.csv","d.csv","e.csv","f.csv"...]

这里是我正在处理的文件类型的一个例子: https://dl.dropboxusercontent.com/u/45095175/test.csv

Here's an example of the type of file that I'm working with: https://dl.dropboxusercontent.com/u/45095175/test.csv

推荐答案

第一种方法:您需要将所有csv文件放在当前文件夹中。您还需要使用 os 模块。

First method: you need to put all your csv files in the current folder. You also need to use the os module.

import os
for f in os.listdir('.'):                 # loop through all the files in your current folder
    if f.endswith('.csv'):                # find csv files
        fn, fext = os.path.splitext(f)    # split file name and extension

        dat = pd.read_csv(f)              # import data
        # Run the rest of your code here

        plt.savefig('{}.jpg'.format(fn))  # name the figure with the same file name 

第二种方法:如果您不想使用 os 模块,可以将您的文件名像这样的列表:

Second method: if you don't want to use the os module, you can put your file names in a list like this:

files = ['a.csv', 'b.csv']

for f in files:
    fn = f.split('.')[0]

    dat = pd.read_csv(f)
    # Run the rest of your code here

    plt.savefig('{}.jpg'.format(fn))

这篇关于使用几个.csv文件在python中自动制作多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆