0
0

More than 3 years have passed since last update.

python備忘録 超基礎

Last updated at Posted at 2020-03-02

import不要な構文の書き方

# listの生成
list = [0,1,2]
print(list)

[0, 1, 2]

#listの追加

list2 = [[0,1,2]]
list2.append([3,4,5])
list2

[[0, 1, 2], [3, 4, 5]]

#list

len([0,1,2])

3

#list

[0,1,2].count(0)

1

#辞書 {key:value}の形式で作成
#メソッドgetに指定するとvalueを返す

{"宮迫" : "謹慎", "田村" : "復帰"}.get("宮迫")

'謹慎'

#list スライスでの指定
#[:3]で0から3番目の手前まで指定

[0, 1, 2, 3, 4, 5][:3]

[0,1,2]

#UDF関数の作り方

def printHello():
    return print("Hello, world!!")

printHello()

'Hello, world!!'

#if文での条件分岐

x = 10
if x <= 20:
    print("xは20以下です。")

if x <= 30:
    print("xは30以下です。")

elif x >=40:
    print("xは40以上です。") #この文は表示されない

'xは20以下です。'
'xは30以下です。'

#for文

x = 0
for i in range(100):
    x += i

4950

numpy

moduleのimport

# numpyモジュールのインポート
import numpy as np
example1 = np.array([2, 4, 6, 8, 10])
example1

array([ 2, 4, 6, 8, 10])

#print("{}".format()) はコメント付けれるので中身を確認しやすい

print("example1:\n{}".format(example1))

example1:
[ 2 4 6 8 10]

# ネストされたリストを渡した場合

example2 = np.array([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]])
example2

array(
[[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10]])

# example2の次元と形
# shapeはlistには使えないので注意!ndarrayに入れよう

print(example2.ndim, example2.shape)

2 (2, 5)

# 行列置換

example2.transpose()

array(
[[ 1, 2],
[ 2, 4],
[ 3, 6],
[ 4, 8],
[ 5, 10]])

# ndarray → list変換

np.array([1,2,3,4,5][2,3,4,5,6]).tolist()

pandas

moduleのimport

# pandasモジュールのインポート
import pandas as pd
data = pd.DataFrame({"area" : [18, 19, 20], "age" : [5, 4, 10]}, index = ["A", "B", "C"])
data

image.png

# データフレームの先頭n行のみ参照する。
data.head(1)

image.png

# データフレームからvaluesのnumpy配列 / 列名のnumpy配列を取得する。
data.values, data.columns

(array([
[ 5, 18],
[ 4, 19],
[10, 20]]),
Index(['age', 'area'], dtype='object'))

#要約統計量
data.describe()

image.png

#相関係数
data.corr()

image.png

# 列の削除
data = data.drop("time", axis = 1)
data

image.png

# 列選択
data[["age","area"]]

image.png

# 条件指定
data[(data["age"]<=5) & (data["area"]==18)]

image.png

# ndarray→dataframe

A = np.array([[1,2],[2,3],[3,4]])

# cloumns命名
B = pd.DataFrame(A,columns={"NO_1","NO_2"})

# cloumns名変更
B.rename(columns={"NO_1":"no1","NO_2":"no2"})

image.png
image.png

# 集計
B.groupby("NO_1",as_index=False).sum()

image.png

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