1. 程式人生 > >python自學筆記15之例項之繪圖、dataframe操作、讀寫csv,excle

python自學筆記15之例項之繪圖、dataframe操作、讀寫csv,excle

用Python繪圖,藉助強大的numpy和matplotlib

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
x = 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_yahoo
from datetime import
date import pandas as pd today = 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 of

quotes_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.305395
1     137.217722
2     135.060600
3     136.495473
4     139.259276
5     139.394094
6     138.199971
7     132.816810
8     135.166530
9     135.243571
10    135.301350
11    134.839113
12    137.275500
13    136.370279
14    134.723651
...
238    156.990005
239    158.630005
240    158.899994
241    158.059998
242    157.669998
243    157.070007
244    156.839996
245    157.139999
246    156.710007
247    156.729996
248    154.970001
249    153.699997
250    154.470001
251    154.449997
252    150.020004
Name: 1, Length: 253, dtype: float64

注意不是索引是列名

建立一個DataFrame讀入singer.csv

from matplotlib.finance import quotes_historical_yahoo
from datetime import date
import pandas as pd
df = 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 stones
1              beatless
2          guns n roses
3             metallica
Name: 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