0
0

More than 1 year has passed since last update.

[pandas] read_csv の備忘録

Last updated at Posted at 2022-09-06

pandasのread_csvについて。
いい例はないものかと思い、せっかくなので太陽黒点数使ってみた。

公式のdocumentation

目次

  • 動作環境
  • 今回使用しているcsvデータ
  • read_csvの使用例

動作環境

種類 バージョン
MacBook Air Monterey12.5.1
python 3.8.9
jupyter notebook 6.4.10
pandas 1.4.3

まずはパッケージのインポートから

import pandas as pd

pandasを扱うときはpdが慣例だそう。

今回使用しているcsvデータ

せっかくなので太陽黒点の1日の個数の年平均データを使ってみた。
Sunspot Number | SILSO
このHP中のTotal Sunspot Number->Yearly mean total sunspot number [1700 - now]からcsvの箇所をクリックしてDLできる。
テキストで一例を示すと

2021.5;  29.6;  7.9; 15233;1

で、上記のcsvと同じ行にあるINFOから確認をすると左から順に

  1. 年(平均を取っているので.5)
  2. 黒点の全球平均個数
  3. 各観測所の観測個数の標準偏差の年平均
  4. 観測値点数
  5. 確定=1, 暫定=0
    という値を示している。

read_csvの使用例

df_SN = pd.read_csv('SN_y_tot_V2.0.csv'
                    , sep=';'
                    , dtype={0:float, 1:float, 2:float, 3:int, 4:int}
                    , names=('', '個数', '標準偏差', '観測値点数', '確定or暫定'))

順に、
csvファイル名: 相対パス
sep= :csvファイル内の値の分割基準を指示(今回は';'、デフォルトは',')
dtype= :各columnのデータ型を辞書型で指定。数字はcolumnの名称でもOK
names= :各columnの名称を指定できる。
となる。実際にデータ型をみてみると、

print(df_SN.dtypes)
# 年         float64
# 個数        float64
# 標準偏差      float64
# 観測値点数       int64
# 確定or暫定      int64
# dtype: object

となり、うまくいっている。

上記以外の利用法

今回のデータは元々ヘッダーが存在していない。このときに何も指定せずに読み込むと...

df_SN = pd.read_csv('SN_y_tot_V2.0.csv', sep=';')
df_SN.head()
#   1700.5	8.3	    -1.0	-1	1
# 0	1701.5	18.3	-1.0	-1	1
# 1	1702.5	26.7	-1.0	-1	1
# 2	1703.5	38.3	-1.0	-1	1
# 3	1704.5	60.0	-1.0	-1	1
# 4	1705.5	96.7	-1.0	-1	1

となりヘッダーとして自動的に最上段の行が出ている。
header=Noneとして読み込むと、

df_SN = pd.read_csv('SN_y_tot_V2.0.csv', sep=';', header=None)
df_SN.head()
#        0	   1	   2	 3	4
# 0	1700.5	 8.3	-1.0	-1	1
# 1	1701.5	18.3	-1.0	-1	1
# 2	1702.5	26.7	-1.0	-1	1
# 3	1703.5	38.3	-1.0	-1	1
# 4	1704.5	60.0	-1.0	-1	1

のようにcolumnに自動で数字を割り当てるようになる。

参考にしたURL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0