知っていることだけ

勉強していて役に立つ、理解の助けになるようなポイントを書いていきます。

Kaggleで使う構文 欠損データへの処理

使用する構文

データが欠損しているかを調べる

<DataFrame>.isnull()

データが無いマスにTrue,あるマスにFalseが入ったデータフレームが得られます。

pandas並び替え

<DataFrame>.sort_values(by = <列名>)

defaultは昇順。引数に ascending = False と加えれば降順になる

NAを埋める

<DataFrame>.fillna(<埋める値>)

グループ毎に別の値を埋める

<DataFrame>.groupby(<groupする対象列>)[<処理対象の列>].transform(<対象の列に行う処理を記した関数>)

各値が何個あるか

<DataFrameの列>.value_counts()

出力例

RL         2263
RM          460
FV          139
RH           26
C (all)      25
Name: MSZoning, dtype: int64

最頻値の取得

<DataFrame>.mode()[0]

Kaggleで使う構文 データの様子を探る

importしたもの

import pandas as pd
import seaborn as sns

使用した構文

列名を羅列

<DataFrame>.columns

出力例

Index(['Id', 'MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea', 'Street',
       'Alley', 'LotShape', 'LandContour', 'Utilities', 'LotConfig',
       'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType',
       'HouseStyle', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd',
       'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType',
       'MasVnrArea', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual',
       'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1',
       'BsmtFinType2', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'Heating',
       'HeatingQC', 'CentralAir', 'Electrical', '1stFlrSF', '2ndFlrSF',
       'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath',
       'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'KitchenQual',
       'TotRmsAbvGrd', 'Functional', 'Fireplaces', 'FireplaceQu', 'GarageType',
       'GarageYrBlt', 'GarageFinish', 'GarageCars', 'GarageArea', 'GarageQual',
       'GarageCond', 'PavedDrive', 'WoodDeckSF', 'OpenPorchSF',
       'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'PoolQC',
       'Fence', 'MiscFeature', 'MiscVal', 'MoSold', 'YrSold', 'SaleType',
       'SaleCondition', 'SalePrice'],
      dtype='object')

describe

<DataFrame>.describe()

出力例

count      1460.000000
mean     180921.195890
std       79442.502883
min       34900.000000
25%      129975.000000
50%      163000.000000
75%      214000.000000
max      755000.000000
Name: SalePrice, dtype: float64

ヒストグラムと推定される確率分布関数を表示

sns.distplot(<DataFrame>[列名]);

出力例

f:id:protoidea:20190408152526p:plain
sns.distplot

Dataframeの結合

<名前> = pd.concat(<Dataframe1>, <Dataframe2>, axis = 1)

axis = 0 なら行を追加、1なら列を追加

散布図

<DataFrame>.plot.scatter(x = <x軸とする列名>, y = <y軸とする列名> , ylim = (<y軸の最小値>, <最大値>))

出力例

f:id:protoidea:20190408152704p:plain
data.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));

複数データを同時に表示

sns.pairplot(<DataFrame>)

出力例

f:id:protoidea:20190410134824p:plain
sns.pairplot(df_train[cols])

箱ひげ図

sns.boxplot(x = <xのlabel名>, y = <label y>, data = <2列のDataFrame>)

出力例

f:id:protoidea:20190408152932p:plain
sns.boxplot(x=var, y="SalePrice", data=data)

相関行列の取得

<名前> = <Dataframe>.corr()

ヒートマップ

sns.heatmap(<相関行列>);

その他引数

  • annot = True にするとヒートマップ上に数値が表示される
  • square=True にすると正方形の形で示される
  • fmt='.2f' でヒートマップ上の数値の表示桁数を変えられる。`.2f`の数字を変えればよい
  • annot_kws = {"size": 値} で数値の表示サイズが変わる

出力例

f:id:protoidea:20190408153454p:plain
sns.heatmap(corrmat, vmax=.8);

dataframeのうち値が大きいものをn行取得

<名前> = <DataFrame>.nlargest(<n>, <対象列名>)

行名取得

<名前> = <DataFrame>.index

数値データのみの列名を取得

<DataFrame>.dtypes[<DataFrame>.dtypes != "object"].index

python3 練習問題

10進数を2進数に変換して表示

実行結果

10進数> 1000
1000 = 1111101000

答え

print("10進数> ", end = '')
a = int(input())
print("{0} = {0:b}".format(a))

金額を入力して貨幣枚数に変換。

枚数が最小になる組み合わせを答える。二千円札を除く

実行結果

金額(円)> 48676
金額: 48676円
一万円札 = 4枚
五千円札 = 1枚
千円札 = 3枚
五百円札 = 1枚
百円札 = 1枚
五十円札 = 1枚
十円札 = 2枚
五円札 = 1枚
一円札 = 1枚

答え

print("金額(円)> ", end= "")
money = int(input())
print("金額: {}円".format(money))
strs = ["一万", "五千", "千", "五百", "百", "五十", "十", "五", "一"]
num = [10000, 5000, 1000, 500, 100, 50, 10, 5, 1]
for s, n in zip(strs, num):
    a = int(money / n)
    print("{}円札 = {}枚".format(s, a))
    money = money % n

うるう年の判定

  1. 年が400で割り切れるなら、うるう年
  2. それ以外で年が100で割り切れるならば、うるう年ではない
  3. それ以外で年が4で割り切れるならば、うるう年

実行結果

year> 2000
2000年はうるう年

答え

print("year> ", end = "")
year= int(input())
is_leap = False
if year % 400 == 0:
    is_leap = True
elif year % 100 == 0:
    is_leap = False
elif year % 4 == 0:
    is_leap = True
print("{}年は".format(year), end = "")
if is_leap:
    print("うるう年")
else:
    print("うるう年ではない")

じゃんけん

実行結果

例1

じゃんけん(0:グー, 1:チョキ, 2:パー)> 0
わたしはグー
あなたはグー
あいこ

例2

じゃんけん(0:グー, 1:チョキ, 2:パー)> 1
わたしはグー
あなたはチョキ
あなたの負け

答え

from random import randint
def say(x):
    ans = ""
    if x == 0:
        ans = "グー"
    elif x == 1:
        ans = "チョキ"
    else:
        ans = "パー"
    return ans

me = -1
while me < 0 or me > 2:
    print("じゃんけん(0:グー, 1:チョキ, 2:パー)> ", end = "")
    me = int(input())
enemy = randint(0,2)
print("わたしは"+ say(enemy))
print("あなたは"+ say(me))
a = (me - enemy ) % 3
if a == 0:
    print("あいこ")
elif a == 1:
    print("あなたの負け")
else:
    print("あなたの勝ち")

3つの数を昇順に並べ替える

実行結果

num[0]> 10
num[1]> 41
num[2]> 12
[10, 12, 41]

答え

num = []
for i in range(3):
    print("num[{}]> ".format(i), end = "")
    num.append(int(input()))
num.sort()
print(num)

素数をpython3で列挙する方法4通り あなたはいくつ答えられる?

問 1000以下の素数を全て求めよ

結果が [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
count: 168 となればよい

以下答え。実行にかかった時間も参考に記録しておく

自身より小さい数全てで割って、割り切れないものを探す(level1)

%%time #jupyter notebookではこれを入れると計算時間を計測できる。無くても結果に支障はない
nums=[]
from math import sqrt
for i in range(2,1001):
    is_prime = 1
    for j in range(2, i):
        if i%j == 0:
            is_prime = 0
            break
    if is_prime == 1:
        nums.append(i)
print(nums)
print("count:", len(nums))

実行時間:20ms

自身の平方根以下の値で割り切れないものを探す(level2)

%%time
nums=[]
from math import sqrt
for i in range(2,1001):
    is_prime = 1
    for j in range(2, round(sqrt(i))+1):
        if i%j == 0:
            is_prime = 0
            break
    if is_prime == 1:
        nums.append(i)
print(nums)
print("count:", len(nums))

実行時間:4ms

エラトステネスの篩を使う(level3)

%%time
from math import floor
#要素番号と入っている値が同じである配列を用意.
#この配列から素数でないものを0にしていく
a = list(range(1001))
#1は素数でない.1でふるいにかけると全て消えるので事前に消去
a[1] = 0
for i in a:
    if i == 0: #すでにふるいにかけられて消えていたらスキップ
        continue
    for j in range(2, floor(1000/i)+1):
        a[i * j] = 0 #iの倍数の値は素数でないので消す
#素数だけ取り出す
b = [i for i in a if i]
print(b)
print("count:", len(b))

実行時間:0ns

番外編 ジェネレータで無限に生成(level4)

%%time
from itertools import count
def primes():
    g = count(2)#2から整数を順に作成する
    while True:
        prime = next(g)
        yield prime
        #filterがループによってどんどん積み重なっていく。素数で割り切れるものを省いていく
        g = filter(lambda x, y=prime: x % y, g)

gen = primes()
num =  next(gen)
arr = []
while(num <= 1000):
    arr.append(num)
    num = next(gen)
print(arr)
print("count:", len(arr))

実行時間:8ms

和の計算法5通り あなたはいくつ思いつく? python初心者用問題

問 「1から10までの和を計算」するプログラムをpythonで5通り作成せよ。

以下答え。プログラムの結果は全て 55

forを使い、C言語風にやる (level1)

s = 0
for i in range(11):
    s+=i
print(s)
説明

range(引数) で0, 1,..., 引数-1 というリストが手に入る

sumを使う (bestなコード) (level2)

s = sum(range(11))
print(s)

ジェネレータ式を使用(level3)

s = sum(i for i in range(11))
print(s)
説明

ジェネレータ式とは、リスト等を受け取る関数の引数にfor文を直接書くやり方のこと

式 for ターゲットリスト in 反復可能オブジェクト
の形で得られる。

reduce(畳み込み)を使用(level4)

from functools import reduce
s = reduce(lambda x,y: x+y, range(11))
print(s)
説明

reduce(適用する関数, 反復可能オブジェクト)

で反復オブジェクトに繰り返し関数を適用した結果を返す。関数はラムダ式でもよい。

番外編 等差数列の公式を使う

s= (1+10)/2*10
print(s)
説明

和=(初項+末項)/2*項数

GNU Make 第3版 紹介

GNU Make 第3版

GNU Make 第3版

 

この記事は次の読者を対象にしています

  • GNU Make 第3版 を読むか迷っている
  • makeの書き方、使い方についての参考書を探している

紹介

この本はmakeの書き方,使い方についての参考書である。GNU Makeと銘打ってあるが、GNU以外のmakeファイルを書くときにも使える知識が載っている。自分が読んだのは2章までだが、使うに値するmakeファイルを書くことができるようになった。

ただ、内容はかなり難しく、2章で挫折した。makeを専門的に扱う人でないと読みきることは難しいと思う。

簡単なmakeファイルを書くだけなら難しい部分は飛ばしても問題ないので、makeの書き方が分からない人は2章までだけでも読むべきだと思う。基礎事項は普通にわかりやすかった.

この本の総合評価:3

まとめ この本を読むべき人は

  • 取り敢えず使えるmakeが書きたい。
  • 図書館などで借りられるから、2章くらいで読むのを止めても損した気分にはならない
  • makeのかなり専門的な事項が知りたい
GNU Make 第3版

GNU Make 第3版

 

基礎からしっかり学ぶC++の教科書 C++14対応 紹介

基礎からしっかり学ぶC++の教科書 C++14対応

基礎からしっかり学ぶC++の教科書 C++14対応

 

 

この記事は次の読者を対象にしています

  • 基礎からしっかり学ぶC++の教科書 C++14対応 を読むか迷っている
  • C++の参考書を探している

紹介

この本はC++の入門書としては少し難しく、中級レベルの人向けである。コンテナの説明やエラー処理、並列処理まで掲載されており、入門書として読むには適していない。また、基礎とは言いつつかなり厳密な説明まで入るので、全体的に中級者向けである。

初級レベルを卒業したい人が知識を得るために読むものと思った方がいい。

この本の総合評価:2

まとめ この本を読むべき人は

  • C++初級レベルは分かる。C++をさらに使いこなしたい!という人
基礎からしっかり学ぶC++の教科書 C++14対応

基礎からしっかり学ぶC++の教科書 C++14対応