Startup Data scientist Blog

データ分析系のテック情報を発信します

UNIX シェルを使ったファイル操作

data という名前の新しいディレクトリを作成します。

mkdir data

 

wget コマンドを使用して、Gitからデータセットをダウンロード

wrangling-shell/main/NASA-logs-1995.txt
wrangling-shell/main/NASA-software-API.txt

 

cdコマンドで作成したディレクトリに移動

cd data

 

lsコマンドでファイルがダウンロード出来ているのか確認

ls

NASA-software-API.txt ファイルと NASA-logs-1995.txt ファイルが表示される。

 

 

Head と tail コマンド

tailコマンドによりファイルの最後の 5 行を表示する。-n フラグを指定してコマンド tail コマンドを入力する。

tail -n 5  NASA-software-API.txt

 

headコマンドによりファイルの先頭の5行を表示する。-n フラグを指定してコマンド headコマンドを入力する。

head -n 5 NASA-software-API.txt

 

nlコマンド

フィルターコマンド。テキストファイルを行番号付きで出力する。

nl -s = NASA-software-API.txt

 

Output

697=SSC-00424 SSC 2013-09-06T00:00:00.000 "General Public" "SSC Site Status Mobile Application"
698=GSC-14732-1 GSFC 2004-06-09T00:00:00.000 "Open Source" "Tool For Interactive Plotting, Sonification, And 3D Orbit Display (TIPSOD)"
699=GSC-14730-1 GSFC 2004-06-09T00:00:00.000 "Open Source" "Space Physics Data Facility Web Services"
700=GSC-14726-1 GSFC 2004-06-09T00:00:00.000 "Open Source" "Earth Observing System (EOS) Clearinghouse (ECHO)"

 

nl -b a NASA-software-API.txt

 

Output

703  GSC-14726-1 GSFC 2004-06-09T00:00:00.000 "Open Source" "Earth Observing System (EOS) Clearinghouse (ECHO)"

 

 

wcコマンド

ファイル内の文字の数をカウントする。

wc NASA-software-API.txt

 

Output

703    8917   81115 NASA-software-API.txt

このファイルには行数 703、単語数 8,917、文字数 81,115 が含まれているということを意味する。

NumPy を使った基本コード

NumPyは数値計算ライブラリーです。プログラミング言語Pythonにおいて数値計算を効率的に行うための拡張モジュールです。

import numpy as np

data = [50,50,47,97,49,3,53,42,26,74,82,62,37,15,70,27,36,35,48,52,63,64]
grades = np.array(data)

print(data)
print(grades)
print(type(data), 'x 2:', data * 2)
print('---')
print(type(data), 'x 2:', grades * 2)
 
Output
[50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15, 70, 27, 36, 35, 48,
52, 63, 64]
[50 50 47 97 49  3 53 42 26 74 82 62 37 15 70 27 36 35 48 52 63 64]
<class 'list'> x 2: [50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82, 62, 37, 15,
70, 27, 36, 35, 48, 52, 63, 64, 50, 50, 47, 97, 49, 3, 53, 42, 26, 74, 82,
62, 37, 15, 70, 27, 36, 35, 48, 52, 63, 64]
---
<class 'list'> x 2: [100 100  94 194  98   6 106  84  52 148 164 124  74  
30 140  54  72  70
  96 104 126 128]
 

 

 

 

pythonを使ってプログラムを複数のコード ファイルに分割する

プログラムを複数のコード ファイルに分割することで、コードのモジュール性を高め、プログラム全体でコードを再利用することができます。 モジュールを使用すると、複数のプログラムで同じコードを共有することもできます。

 

pythonを使ったモジュールを定義

作成ファイル1 touch test.py

作成ファイル2 touch main.py

 

 touchコマンドは 空のファイルを作成したり、時刻を変更するコマンドです。

作成したファイルは同じディレクトリ内に入れておかないと起動しません。

 

 

test.pyファイル

def create_deck():
  suits = ["Hearts", "Spades", "Clubs", "Diamonds"]
  ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
  deck = []

  for  suit in suits:
    for rank in ranks:
      deck.append(f'{rank} of {suit}')

  return deck

 

main.pyファイル

import test

cards = test.create_deck()

for card in cards:
  print(card)

 

 

Output

2 of Hearts
3 of Hearts
4 of Hearts
5 of Hearts
6 of Hearts
7 of Hearts
8 of Hearts
9 of Hearts
10 of Hearts
Jack of Hearts
Queen of Hearts
King of Hearts
Ace of Hearts
2 of Spades
3 of Spades
4 of Spades
5 of Spades
6 of Spades
7 of Spades
8 of Spades
9 of Spades
10 of Spades
Jack of Spades
Queen of Spades
King of Spades
Ace of Spades
2 of Clubs
3 of Clubs
4 of Clubs
5 of Clubs
6 of Clubs
7 of Clubs
8 of Clubs
9 of Clubs
10 of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Clubs
2 of Diamonds
3 of Diamonds
4 of Diamonds
5 of Diamonds
6 of Diamonds
7 of Diamonds
8 of Diamonds
9 of Diamonds
10 of Diamonds
Jack of Diamonds
Queen of Diamonds
King of Diamonds
Ace of Diamonds

 

 

 

pythonで任意の引数リストとキーワード引数を関数に追加する方法

def print_args(*args):
    for arg in args:
        print(f'arg = {arg}')

print_args('a')
print_args('a', 'b')
print_args('a', 'b', 'c')
 
Output
arg = a
arg = a
arg = b
arg = a
arg = b
arg = c
 

関数定義の後にコードによって print_args() が 3 回呼び出され、毎回異なる値が渡されている。

 

 

def print_args(*args):
    print(args)
    print(type(args))
   
print_args('a')
print_args('a', 'b')
print_args('a', 'b', 'c')
 
Output
('a',)
<class 'tuple'>
('a', 'b')
<class 'tuple'>
('a', 'b', 'c')
<class 'tuple'>

引数リストは型 list ではなく、型 tuple で表示される。

タプル型とは、複数のデータの組み合わせから構成されているデータを表現する場合をタプル という種類のオブジェクトを利用する。

 

 

print_keyword_args() 関数を 3 回呼び出します。'third' が存在しない場合は表示が行われず、存在している場合のみ出力されます。

def print_keyword_args(**kwargs):
   
    third = kwargs.get('third', None)
    if third != None:
        print('third arg =', third)
       
print_keyword_args(first='a')
print_keyword_args(first='b', second='c')
print_keyword_args(first='d', second='e', third='f')
 
Output
third arg = f

 

 

キーワードと値を反復処理するようにコード例

def print_keyword_args(**kwargs):
   
    print('\n')
   
    for key, value in kwargs.items():
        print(f'{key} = {value}')
       
    third = kwargs.get('third', None)
    if third != None:
        print('third arg =', third)
   
       
print_keyword_args(first='a')
print_keyword_args(first='b', second='c')
print_keyword_args(first='d', second='e', third='f')
 
Output

 

first = a


first = b
second = c


first = d
second = e
third = f
third arg = f

 

getメソッドとは、

辞書型.get(キー, キーが存在しない場合の返り値)を取り出すメソッドです。

 

 

kwargs の値およびそのデータ型を出力するようにコード

def print_keyword_args(**kwargs):
   
    print('\n')
    print(kwargs)
    print(type(kwargs))
   
    for key, value in kwargs.items():
        print(f'{key} = {value}')
       
    third = kwargs.get('third', None)
    if third != None:
        print('third arg =', third)
   
       
print_keyword_args(first='a')
print_keyword_args(first='b', second='c')
print_keyword_args(first='d', second='e', third='f')
 
Output

 

{'first': 'a'}
<class 'dict'>
first = a


{'first': 'b', 'second': 'c'}
<class 'dict'>
first = b
second = c


{'first': 'd', 'second': 'e', 'third': 'f'}
<class 'dict'>
first = d
second = e
third = f
third arg = f

 

typeによってkwargs のデータ型は dict であることがわかります。