0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CASTableでカラムを指定して取得するloc/iloc/ixの使い方

Posted at

SAS ViyaはAIプラットフォームです。PythonやJava、Rなどの言語を通して利用できます。そのSAS Viyaの中で使われているのがCASTableというテーブルオブジェクトです(CASはCloud Analytic Servicesの略です)。今回はCASTableでloc/iloc/ixを使って列を指定してデータを取得する方法を解説します。

データベースからテーブルを取得する

まずはSAS Viyaに接続します。

import swat
conn = swat.CAS('server-name.mycompany.com', 5570, 'username', 'password')

次にCASTableを取得します。今回はIRISデータのCSVを利用します。

tbl = conn.loadtable('data/iris.csv', caslib='casuser').casTable

列を指定する

列を指定する際には loc を使い、2つ目の引数にカラム名を指定します。

tbl.loc[:, 'petal_width'].head()

そうすると、指定されたカラムの値だけが取得できます。

0    2.0
1    2.3
2    2.0
3    2.3
4    2.2
Name: petal_width, dtype: float64

これは複数カラム指定できます。

tbl.loc[:, 'sepal_length':'petal_length'].head()

複数カラムの場合はヘッダー行が表示されます。範囲で指定しますので、間に存在するsepal_widthも表示されます。

sepal_length sepal_width petal_length
0 7.9 3.8 6.4
1 7.7 2.6 6.9
2 7.7 2.8 6.7
3 7.7 3.0 6.1
4 7.7 3.8 6.7

もしカラムを特定したい場合には配列で指定してください。

tbl.loc[:, ['petal_width', 'sepal_width']].head()
petal_width sepal_width
0 2.0 3.8
1 2.3 2.6
2 2.0 2.8
3 2.3 3.0
4 2.2 3.8

カラム名ではなく数字でも指定できます。

tbl.loc[:, 3].head()
0    2.0
1    2.3
2    2.0
3    2.3
4    2.2
Name: petal_width, dtype: float64

複数カラム指定も同様です。

tbl.iloc[:, 0:3].head()
sepal_length sepal_width petal_length
0 7.9 3.8 6.4
1 7.7 2.6 6.9
2 7.7 2.8 6.7
3 7.7 3.0 6.1
4 7.7 3.8 6.7

カラムを特定する場合は配列というのも同じです。

tbl.iloc[:, [3, 1]].head()
petal_width sepal_width
0 2.0 3.8
1 2.3 2.6
2 2.0 2.8
3 2.3 3.0
4 2.2 3.8

数字とカラム名の組み合わせも可能です。

tbl.ix[:, [3, 'sepal_width']].head()
petal_width sepal_width
0 2.0 3.8
1 2.3 2.6
2 2.0 2.8
3 2.3 3.0
4 2.2 3.8

まとめ

一部のデータだけ見て分析したい場面は多いでしょう。そんな時にはlocやiloc、ixを使って素早くデータを抽出してください。数字はループ処理に使うのも簡単なので、分析や計算処理の自動化にも使えるはずです。

SAS for Developers | SAS

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?