5
9

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 3 years have passed since last update.

Pandasの備忘録

Last updated at Posted at 2020-08-27

はじめに

  • 普段よく使うPandasの用途別の使い方について、自分の備忘録としてまとめる。
  • 定期的に更新予定。

備忘録

seriesのループ(値+index)

# dataframeから列を取り出してseriesへ
aaa = df['sts']

# 先頭行は”初回”と出力
for index, item in enumerate(aaa):
    if index < 1:
        print("初回")
    else:
        print("2回目以降")

dataframeからカラム抽出

# 取り出す列を配列で定義
use_idx = ['aaa','bbb','ccc']

# 定義した列を抽出して新しいdataframeを作成
df2 = df[ use_idx ]

曜日抽出

# 日付をdatatime型に変換
data['date'] = pd.to_datetime(date['date'])

# 日付から曜日を抽出(SUN=6、MON=0)
date['day_of_week'] = date['date'].dt.dayofweek

list→series変換

data = [1,8,14,56]
# オプションのnameでカラム名をつける
 s = pd.Series(data, name=['day', 'hour', 'c1', 'c2'])

カラム名をlistに抽出

 name = df.columns.values

カラムの削除

df = df.drop('AAAA', axis = 1)

カラム名の一括入れ替え

# 既存のカラム名に文字列を結合
newcol = []
for i in df.columns:
    print(i + "_2day")
    newcol.append(i + "_2day")

# カラム名を再指定
df.columns = newcol

dataframeの並べ替え

# 並べ替え
dfl = df.sort_values(by="A")  

# 複数の並べ替え
dfl = df.sort_values(by=["A","B","C","D"])  

dataframeの結合(concat)

# 列で結合
df_union = pd.concat( [df, df2], axis=1 )

# 行で結合
df_union = pd.concat( [df, df2], axis=0 )  
列の順序の入れ替わり対策としてsort=Falseオプションをつけること

dataframeの結合(merge)

# keyを条件に内部結合
df = pd.merge(left, right, on='key')

# keyを条件に左外部結合
df = pd.merge(left, right, on='key', how = 'left')

"""
結合方法は how キーワードで指定する。
inner: 既定。内部結合。両方のデータに含まれるキーだけを残す。
left: 左外部結合。ひとつめのデータのキーをすべて残す。
right: 右外部結合。ふたつめのデータのキーをすべて残す。
outer: 完全外部結合。すべてのキーを残す。
"""

indexの設定

# indexをxxxx列に設定
df.set_index('xxxx')

# indexをリセット
# 連番がインデックスに設定され元のインデックスがデータ列に追加
df.reset_index('xxxx')

# indexをリセット
# 古いindexは削除され新しいindexが設定さえる
df.reset_index(drop=True)

"""
df2 = df.reset_index(drop=True)
上記のようにしないとreset_indexが反映されないので注意()
"""

dataframeとseriesの結合

# dataframeのdfとseriesのdf_serを結合
# seriesはto_frame()を使用してdataframeに変換
 df2 = pd.concat( [ df, df_ser.to_frame() ], axis=1 )

timestmap→datetime変換

  • pandasにおけるdatetime型はtimestampであり、ほぼ同様の使い方ができる
  • datetime型に変更する場合は以下の関数を用いるとよい。
to_pydatetime()

csv読取時の方を文字列で

list→dataframe変換

hoge = pd.DataFrame(hoge)

dataframeのindexで並べ替え

# 昇順
hoge = hoge.sort_index() 
# 降順
hoge = hoge.sort_index(ascending=False) 

read_sqlでパラメータ付与(ワイルドカード利用)

# パラメーターが1つ
sql "select * from aaa where opstime >= %s;"
df = pd.read_sql(sql, con=conn, params=("2020-02-13"))

# パラメーターが2つ
sql "select * from aaa where opstime >= %s and opstime <= %s;"
df = pd.read_sql(sql, con=conn, params=("2020-02-13","2020-02-15"))

空のデータフレームを作成

# 3行・3列で、値がNULLのデータフレームを作成
df = pd.DataFrame(index=range(3), columns=['a', 'b' , 'c'])

条件でデータ抽出

# nameがTaroのデータを抽出
df.query("name=='Taro'")

dataframeに列追加

# dataframeを引数にすることで、関数内で複数の引数を扱うのと同じことが可能
def check(row):
    val = 0    
    if row['aaa'] == 1 and row['bbb'] == 1:
        val = 1
    else:
        val = 0
    return val

df['ccc'] = df.apply(check, axis=1)
5
9
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
5
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?