使用Python有效地以csv格式绘制表格 [英] Efficiently ploting a table in csv format using Python

查看:54
本文介绍了使用Python有效地以csv格式绘制表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python绘制csv格式的表.到目前为止,我可以通过在网站上阅读类似的问题来获得所需的结果,但是我的解决方案似乎并不太"pythonic",也没有找到一种非常简单的方法.我敢肯定,有一种更有效的方式来绘制表格,所以我问这个问题以更多地了解Python,并让其他人对同一问题有一个直接的答案.在这里:

I am trying to plot a csv formatted table using Python. So far, I was able to get the result I wanted by reading similar questions on the site, but my solution doesn't seem too "pythonic", nor did I found a very straightforward way of doing this. I am sure there is a more efficient way for plotting a table, so I'm asking this question to learn more about Python and let others have a straight answer for the same problem. Here it goes:

我有一个带有数据的表,该表具有标题和第一列.就我而言,分别是几个月和几年.即:

I have a table with data, which have headers and a first column. In my case, it is months and years respectively. i.e.:

年,1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,DIC1998,,0.78,0.60,0.50,0.50 ,,,, 0.62,,0.451999,0.40,0.30,0.28,0.22,0.26,0.50,0.52,0.76,0.89,0.85,0.74,0.672000,0.58,0.58,0.51,0.47,0.63,0.92,1.00,1.00,0.99,1.00,0.96,0.912001,0.86,0.83,0.80,0.71,0.83,0.98,1.05,1.11,1.09,0.99,0.87,0.80...

Year,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DIC 1998,,0.78,0.60,0.50,0.50,,,,,0.62,,0.45 1999,0.40,0.30,0.28,0.22,0.26,0.50,0.52,0.76,0.89,0.85,0.74,0.67 2000,0.58,0.58,0.51,0.47,0.63,0.92,1.00,1.00,0.99,1.00,0.96,0.91 2001,0.86,0.83,0.80,0.71,0.83,0.98,1.05,1.11,1.09,0.99,0.87,0.80 ...

如您所见,也缺少数据.

As you can see, there is missing data too.

我的解决方法如下:

import numpy as np
from matplotlib import pyplot as plt

#Import Data
Data=np.genfromtxt('LakeLevels.csv',delimiter=',',names=True,dtype=float)

#Extract data
Months=list(Data.dtype.names[1:])
Years=Data['Year']
Level=Data.view(dtype=float).reshape(Data.shape + (-1,))[:,1:]
Level_masked= np.ma.array (Level, mask=np.isnan(Level))

#Plot
fig=plt.pcolor(np.linspace(1,12,12),Years,Level_masked)
plt.colorbar()
plt.xticks(range(12),Months,rotation=45)

我发现解决方案对于一个非常简单的任务来说太复杂了.有没有更好的方法来达到相同的结果或我可以改进的部分代码?甚至是自动执行此功能的功能.

I found the solution was too complex for a very simple task. Is there a better way of achieving the same result or parts of the code I can improve? Maybe even a function that does this automatically.

谢谢.

推荐答案

我将根据@Ami Tavory的回答发布最终解决方案.

I will post my final solution based on @Ami Tavory's answer.

import pandas as pd
import seaborn as sns

df = pd.read_csv('LakeLevels.csv', delimiter=',', index_col='Year')
sns.heatmap(df)

因此,通过使用这2个程序包(即pandas和seaborn),我能够在2行中获得所需的结果!

So by using these 2 packages (i.e. pandas and seaborn) I was able to get my desired result in 2 lines!

最诚挚的问候.

这篇关于使用Python有效地以csv格式绘制表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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