LoginSignup
1
1

More than 1 year has passed since last update.

Pandasの使い方5

Last updated at Posted at 2021-05-07

1 この記事は

DataFrame型データの各種操作方法をメモする。

題名 リンク
【python】Pandasの使い方 LINK
【python】Pandas2の使い方 LINK
【python】Pandas3の使い方 LINK
【python】Pandas4の使い方 LINK
【python】Pandas5の使い方 LINK
【python】Pandas ,pythonコードメモ 6 LINK

2 内容

2-1 日付から第何週なのかを計算する。

sample.py
import datetime

print("2021/5/3(月)が第何週になるかを自動計算する")
datetime.date(2021, 5, 3).isocalendar()

print("帰り値 -> 年,第何週,曜日。月曜日が1になる")

実行結果

#返り値 -> 年,第何週,曜日。月曜日が1になる
(2021, 18, 1)

2-2 Series型データから実データを抽出する

sample.py
import pandas as pd

s1 = pd.Series([70, 45, 80, 60, 90], 
               index=['国語', '数学', '理科', '社会', '英語'])

print("Series型データを表示する")
print(s1)
print("Series型からindexを抽出する")
print(s1.index)
print("Series型からデータを抽出する")
print(s1.values)


実行結果

Series型データを表示する
国語    70
数学    45
理科    80
社会    60
英語    90
dtype: int64
Series型からindexを抽出する
Index(['国語', '数学', '理科', '社会', '英語'], dtype='object')
Series型からデータを抽出する
[70 45 80 60 90]

2-3 Dataframe型行単位で最大値を取得する

sample.py
import pandas as pd
import numpy as np

dat0 = [
    ['2019-07-01',70,40,55],
    ['2019-07-02',1,46,5],
    ['2019-07-03',200,40,545],
]

df0 = pd.DataFrame(dat0,columns=["A","B","C","D"])



#A,B列をindexに指定する。
df0=df0.set_index(["A"])

display(df0)


print("B,C,D列のMAX値を取得する")
df0['Z(MAX)']=df0[['B','C','D']].apply(np.max,axis=1)
print("B,C,D列のMAX値をとる列名を取得する")
df0['INDEX(MAX)']=df0.columns[ df0[['B','C','D']].apply(np.argmax,axis=1) ]
display(df0)

実行結果

B	C	D
A			
2019-07-01	70	40	55
2019-07-02	1	46	5
2019-07-03	200	40	545
B,C,D列のMAX値を取得する
B,C,D列のMAX値をとる列名を取得する
B	C	D	Z(MAX)	INDEX(MAX)
A					
2019-07-01	70	40	55	70	B
2019-07-02	1	46	5	46	C
2019-07-03	200	40	545	545	D

2-4 Dataframe型 指定行を削除する。

sample.py
import numpy as np
import pandas as pd


dat = [
    ['2019-07-01','9990'],
    ['2019-07-02','9991'],
    ['2019-07-03','9992'],
    ['2019-07-04','9993'],
    ['2019-07-05','9995'],
    ['2019-07-08','9996']
]
df0 = pd.DataFrame(dat,columns=["A","B"])

display(df0)
display(df0.drop(0)) #0行名を削除する。

実行結果


A	B
0	2019-07-01	9990
1	2019-07-02	9991
2	2019-07-03	9992
3	2019-07-04	9993
4	2019-07-05	9995
5	2019-07-08	9996

A	B
1	2019-07-02	9991
2	2019-07-03	9992
3	2019-07-04	9993
4	2019-07-05	9995
5	2019-07-08	9996

2-5 Dataframe型をSerie型に変更 & Series型のindexとデータを取り出す

sample.py
import pandas as pd
import numpy as np

dat0 = [
    ['2019-07-01',70,40,55],
    ['2019-07-02',1,46,5],
    ['2019-07-03',200,40,545],
]

df0 = pd.DataFrame(dat0,columns=["A","B","C","D"])
df0=df0.set_index(["A"])

sdf=df0['B'] #DataFrame型Series型に変更する。


#Series型のindexとvalueを取り出す。
print("index:",sdf.index)
print("value:",sdf.values)



実行結果

#Series型のindexとvalueを取り出す。
index: Index(['2019-07-01', '2019-07-02', '2019-07-03'], dtype='object', name='A')
value: [ 70   1 200]

2-6 日付がその年の第何週にあたるかを算出する。

indexを日付型データにする必要がある。

sample.py
import pandas as pd
import numpy as np

dat0 = [
    ['2019-07-01',70,40,55],
    ['2019-07-02',1,46,5],
    ['2019-07-03',200,40,545],
]

df0 = pd.DataFrame(dat0,columns=["A","B","C","D"])
df0["A"]=pd.to_datetime(df0['A'])  #日付の文字列の列に対してpd.to_datetime()を適用し、datetime64型に変換する。

df0=df0.set_index(["A"])
display(df0)

print("DataFrameのindexがdatetime64であると、その日付が第何週かを算出できる。")

print("date:"+ str(df0.index[0]))
print("type:"+ str(type(df0.index[0])))
print("year:"+ str(df0.index[0].year))
print("week:"+ str(df0.index[0].week))
print("day:"+ str(df0.index[0].day))

実行結果

	B	C	D
A			
2019-07-01	70	40	55
2019-07-02	1	46	5
2019-07-03	200	40	545
date:2019-07-01 00:00:00
type:<class 'pandas._libs.tslibs.timestamps.Timestamp'>
year:2019
week:27
day:1

2-7 条件に合う行を取り出し、要素を書き換える

sample.py
import numpy as np
import pandas as pd


dat = [
    [2020,53],
    [2021,53],
    [2021,53],
    [2021,8],
    [2021,15],
    [2021,7]
]
df0 = pd.DataFrame(dat,columns=["A","B"])

print("初期状態")

display(df0)

print("A列が2021かつB列が53のものに対し、B列を1に書き換える")

df0.loc[(df0.A==2021) & (df0.B==53),"B"]=1

print("書き換え後")
display(df0)

実行結果

初期状態

A	B
0	2020	53
1	2021	53
2	2021	53
3	2021	8
4	2021	15
5	2021	7
A列が2021かつB列が53のものに対し、B列を1に書き換える
書き換え後
A	B
0	2020	53
1	2021	1
2	2021	1
3	2021	8
4	2021	15
5	2021	7

2-8 List型変数に要素を追加する。& List型を結合させる。

sample.py
#list型に要素を追加する。(append)
tmp=[]

for i in range (0,3):
    tmp.append(i)

tmp

#list型を結合させる。(append)

tmp0=[[1,10]]
tmp1=[2,20]
tmp0.append(tmp1)

print(tmp0)

実行結果

#list型に要素を追加する。
[0, 1, 2]

#list型を結合させる。
[[1, 10], [2, 20]]

2-9 累積和を計算する

sample.py
import pandas as pd
import numpy as np

dat0 = [
    ['2019-07-01',10],
    ['2019-07-02',20],
    ['2019-07-03',40],
]

df0 = pd.DataFrame(dat0,columns=["A","B"])

#A,B列をindexに指定する。
df0=df0.set_index(["A"])

df0['cumB'] = df0['B'].cumsum()

display(df0)

実行結果

	B	cumB
A		
2019-07-01	10	10
2019-07-02	20	30
2019-07-03	40	70

2-10 ASSERT文の使い方

sample.py
#assertの使い方、変数の条件が想定外のものになった場合にコードの実行を止める


#assert x in ("A", "B"), 'catch' の意味
#x="A" or "B" の場合は何もしない。xがそれ以外の場合 AssertionErrorを出力してコードの実行を止める。


x="A"
assert x in ("A", "B"), 'xの値はA or B以外なのでAssertionErrorを出力してコードの実行を止める。'
print("xの値はA or Bなのでこのまま進む")

x="B"
assert x in ("A", "B"), 'xの値はA or B以外なのでAssertionErrorを出力してコードの実行を止める。'
print("xの値はA or Bなのでこのまま進む")

x="C"
assert x in ("A", "B"), 'xの値はA or B以外なのでAssertionErrorを出力してコードの実行を止める。'

実行結果

xの値はA or Bなのでこのまま進む
xの値はA or Bなのでこのまま進む
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-3-38ea5d074947> in <module>
     15 
     16 x="C"
---> 17 assert x in ("A", "B"), 'xの値はA or B以外なのでAssertionErrorを出力してコードの実行を止める。'

AssertionError: xの値はA or B以外なのでAssertionErrorを出力してコードの実行を止める。
1
1
1

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
1
1