2019-04-22 實驗課(第九周)
阿新 • • 發佈:2019-04-22
一維數組 date dataframe randn 一行 panda class lis pandas 2019-03-31 -0.047282 0.882888 0.183245 1.202914
2019-04-30 0.448960 -0.801902 0.417301 0.850788
2019-05-31 -0.964697 -0.279292 -1.124437 -1.780033
2019-06-30 0.249203 0.501495 1.036100 -0.175475
2019-07-31 -0.343220 -0.213705 0.048418 -0.266311
2019-08-31 -0.692261 -0.314375 0.155428 -1.395100
2019-09-30 0.838895 -1.284752 -0.449155 -0.696251
2019-10-31 -0.805917 -0.340499 1.241699 -0.432656
2019-11-30 0.217552 2.012787 -0.255996 -1.619652
2019-12-31 -0.430906 1.873066 0.094659 0.461702
一.pandas
生成數組:
(1)一維數組,代碼:
import numpy as np import pandas as pd x = pd.Series([1,3,5,7,9, np.nan]) print(x)
輸出:
0 1.0
1 3.0
2 5.0
3 7.0
4 9.0
5 NaN
dtype: float64
(2)二維數組DataFrame 代碼:
import numpy as np import pandas as pd datas = pd.date_range(start=‘20190101‘, end=‘20191231‘, freq=‘M‘) #M代表月 x = pd.DataFrame(np.random.randn(12,4), index=datas, columns=list(‘ABCD‘)) #random.randn 12行4列隨機數 ,index:列數據 columns第一行=A B C D print(x)
輸出:
A B C D
2019-01-31 -1.032103 -0.365249 0.371243 -0.410856
2019-02-28 0.217511 -0.387334 1.885094 -0.821772
2019-04-30 0.448960 -0.801902 0.417301 0.850788
2019-05-31 -0.964697 -0.279292 -1.124437 -1.780033
2019-06-30 0.249203 0.501495 1.036100 -0.175475
2019-07-31 -0.343220 -0.213705 0.048418 -0.266311
2019-08-31 -0.692261 -0.314375 0.155428 -1.395100
2019-09-30 0.838895 -1.284752 -0.449155 -0.696251
2019-10-31 -0.805917 -0.340499 1.241699 -0.432656
2019-12-31 -0.430906 1.873066 0.094659 0.461702
(3)把數據保存為文件
x.to_csv(‘d:\\test.csv‘)# 保存到d盤,文件名字是test 數據包含在x裏面
(4)讀取csv文件
import numpy as np
import pandas as pd
‘‘‘datas = pd.date_range(start=‘20190101‘, end=‘20191231‘, freq=‘M‘)
x = pd.DataFrame(np.random.randn(12,4), index=datas, columns=list(‘ABCD‘))
print(x)‘‘‘
#前面的可以省略
x = pd.read_csv(‘d:\\test.csv‘)
print(x)
一.讀取csv文件
import csv csvFile = open("Python成績.csv", "r")
二.然後通過 csv.reader()
函數建立一個讀入數據的對象,我起名為reader。
reader = csv.reader(csvFile)
2019-04-22 實驗課(第九周)