python自学笔记15之实例之绘图、dataframe操作、读写csv,excle

来源:互联网 发布:种子文件下载软件 编辑:程序博客网 时间:2024/06/05 20:46

用Python绘图,借助强大的numpy和matplotlib

import numpy as npimport matplotlib.pyplot as pltimport pandas as pdx = np.linspace(0,1)y = np.sin(4*np.pi*x)*np.exp(-5*x)t = pd.DataFrame(y,index = x)t.plot()plt.show()

这里写图片描述

用pandas写csv文件

from matplotlib.finance import quotes_historical_yahoofrom datetime import dateimport pandas as pdtoday = date.today()start = (today.year-1,today.month,today.day)quotes  = quotes_historical_yahoo('IBM',start,today)df = pd.DataFrame(quotes)df.to_csv('stockIBM.csv')

从工作目录下可以看到多了个stockIBM.csv的文件,需要注意的是:
MatplotlibDeprecationWarning: This function has been deprecated in 1.4 in favor ofquotes_historical_yahoo_ochl, which maintains the original argument order, orquotes_historical_yahoo_ohlc, which uses the open-high-low-close order. This function will be removed in 1.5
mplDeprecation)

意味着从matplotlib.finance中导入quotes_historical_yahool的时候出现了警告,
从matplotlib的官方帮助文档:这里,可以看到:

This module is deprecated in 1.4 and will be moved to mpl_toolkits or it’s own project in the future.

matplotlib.finance模块在1.4中不支持有其他变动,其他更详细的文档参看help

读取csv:

result = pd.read_csv('stockIBM.csv')

单独一列的读取显示:

 print(result['1'])0     144.3053951     137.2177222     135.0606003     136.4954734     139.2592765     139.3940946     138.1999717     132.8168108     135.1665309     135.24357110    135.30135011    134.83911312    137.27550013    136.37027914    134.723651...238    156.990005239    158.630005240    158.899994241    158.059998242    157.669998243    157.070007244    156.839996245    157.139999246    156.710007247    156.729996248    154.970001249    153.699997250    154.470001251    154.449997252    150.020004Name: 1, Length: 253, dtype: float64

注意不是索引是列名

创建一个DataFrame读入singer.csv

from matplotlib.finance import quotes_historical_yahoofrom datetime import dateimport pandas as pddf = pd.DataFrame({'singer':['the rolling stones','beatless','guns n roses','metallica'],'song':['satisfaction','let it be','dont cry','nothing else matters']})df.to_csv('singer.csv')result = pd.read_csv('singer.csv')print(result['singer'])0    the rolling stones1              beatless2          guns n roses3             metallicaName: singer, dtype: object

dataframe简单操作

列与列求和直接用+,赋值也是直接赋,千万别想太多

data = {'number':[1001,1002,1003],'name':\['xiaoming','xiaohong','xiaohua'],'python':\[77,88,99],'math':[87,82,91]}df = pd.DataFrame(data)df['sum'] = df['python']+df['math']

注意append的使用,dataframe.append是添加行
注意DataFrame的生成方式,里面用了一个dict类型

读写excel

df.to_excel(‘grade.xlsx’)
pd.read_excel(‘grade.xlse’)
和csv类似

pandas官方文档:help

0 0
原创粉丝点击