熱門文章

2019年11月8日 星期五

使用 numpy.genfromtxt 讀取混合格式的資料

作者:王一哲
日期:2019/11/8




之前我測試過使用 numpy.loadtxt 匯入 csv 檔的資料,但是資料的格式都是浮點數 (float),如果資料中某些欄位的資料格式是字串 (string),處理起來相當麻煩,改用 numpy.genfromtxt 會比較簡單。我匯入的資料檔如下:

行星名稱, a (AU), T (yr)
水星, 0.387, 0.241
金星, 0.723, 0.615
地球, 1.000, 1.000
火星, 1.524, 1.881
木星, 5.203, 11.863
土星, 9.555, 29.458
天王星, 19.218, 84.022
海王星, 30.110, 164.774



我用以下程式碼匯入資料並繪製 XY 散布圖。

import numpy as np
import matplotlib.pyplot as plt

# 從 csv 檔讀取資料, 資料以 ',' 分隔, 略過第1列
data = np.genfromtxt("PlanetsData.csv", delimiter=',', dtype=None,
                     names=('Planet', 'a', 'T'), skip_header=1, encoding='UTF-8')
planet, a, T = data['Planet'], data['a'], data['T']

# a - T 關係圖
plt.figure(figsize=(6, 4.5), dpi=100)
plt.title(r'$a - T ~\mathrm{Plot}$', fontsize=16)
plt.xlabel(r'$T ~\mathrm{(yr)}$', fontsize=14)
plt.ylabel(r'$a ~\mathrm{(AU)}$', fontsize=14)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.subplots_adjust(left=0.12, bottom=0.15)
plt.grid(color='grey', linestyle='--', linewidth=1)
plt.plot(T, a, color='blue', marker='o', markersize=10, markeredgecolor='black', linestyle='')
plt.show()




重點在於第5、6行,以下依序說明每個選項的用途:

  1. "PlanetsData.csv":從 PlanetsData.csv 這個檔案匯入資料
  2. delimiter=',':資料以逗號分隔
  3. dtype=None:不指定資料格式
  4. names=('Planet', 'a', 'T'):將三個欄位的資料分別命名為 Planets、a、T
  5. skip_header=1:忽略第一列的資料
  6. encoding='UTF-8':文字編碼為 UTF-8 格式

將讀取到的資料指定給變數 data,如果用 print(data) 印出資料,輸出結果如下:

[('水星',  0.387,   0.241) ('金星',  0.723,   0.615) ('地球',  1.   ,   1.   )
 ('火星',  1.524,   1.881) ('木星',  5.203,  11.863) ('土星',  9.555,  29.458)
 ('天王星', 19.218,  84.022) ('海王星', 30.11 , 164.774)]



在第7行將三個欄位的資料分別指定給變數 planet、a、T,如果用 print 印出資料,輸出結果如下:

['水星' '金星' '地球' '火星' '木星' '土星' '天王星' '海王星']
[ 0.387  0.723  1.     1.524  5.203  9.555 19.218 30.11 ]
[  0.241   0.615   1.      1.881  11.863  29.458  84.022 164.774]



資料被儲存在三個一維陣列中,如果想要進一步處理數據或是用來繪圖會比較方便,以下是第10 - 19行繪圖的成果。





參考資料https://numpy.org/devdocs/user/basics.io.genfromtxt.html





HackMD 版本連結:https://hackmd.io/@yizhewang/HJjG8ha5r

沒有留言:

張貼留言