Pandasの小技をまとめる01

Pandasの小技をまとめてます。(01)

# データフレームの作成

import pandas as pd

# 辞書(Dictionary)からDataFrameを作成します
dict = {
        "name"  :["taro", "jiro", "saburo"],
        "age"   :["11",   "21",   "22"],
        "color" :["Red",  "Blue", "Green"],
        "flag"  :["True", "True", "False"],
}
df  = pd.DataFrame( dict )
display(df)
name age color flag
taro 11 Red TRUE
jiro 21 Blue TRUE
saburo 22 Green FALSE

# リストで複数条件で抽出

下記のコードで、リストから複数条件で抽出します。

# リストで抽出
_list = ["taro", "jiro"]
df[df["name"].isin(_list)]
name age color flag
taro 11 Red TRUE
jiro 21 Blue TRUE

# 文字列で特定の文字を含む

下記のコードで、文字列で特定の文字を含むものを抽出します。

# 文字列で特定の文字を含む
df[df["name"].str.contains("ro")]
name age color flag
taro 11 Red TRUE
jiro 21 Blue TRUE
saburo 22 Green FALSE

# pandasでfor文を使わない処理(1列)

下記のコードで、pandasでfor文を使わない処理(1列)をします。

#  pandasでfor文を使わない処理(1列)
df["new_columns"] = df["name"].apply(lambda x: x + "_aaa")
display(df)
name age color flag new_columns
taro 11 Red TRUE Red_aaa
jiro 21 Blue TRUE Blue_aaa
saburo 22 Green FALSE Green_aaa

# pandasでfor文を使わない処理(2列)

下記のコードで、pandasでfor文を使わない処理(2列)をします。

#  pandasでfor文を使わない処理(2列)
df["new_columns"] = df[["name", "color"]].apply(lambda x: x[0] + x[1], axis=1)
display(df)
name age color flag new_columns
taro 11 Red TRUE taroRed
jiro 21 Blue TRUE jiroBlue
saburo 22 Green FALSE saburoGreen

# 重複削除

下記のコードで、pandasで重複削除をします。

#  重複削除
df.drop_duplicates(subset="flag")
name age color flag new_columns
taro 11 Red TRUE taroRed
saburo 22 Green FALSE saburoGreen

# カラム削除

下記のコードで、pandasでカラム削除をします。

# カラム削除
df.drop('new_columns', axis=1, inplace=True)
df
name age color flag
taro 11 Red TRUE
jiro 21 Blue TRUE
saburo 22 Green FALSE

# 置換

下記のコードで、置換します。

# 置換
df["color"] = df["color"].str.replace("Red", "Reda")
df
name age color flag
taro 11 Reda TRUE
jiro 21 Blue TRUE
saburo 22 Green FALSE

# 条件置換

下記のコードで、条件で置換します。

# 条件置換
df.loc[df["color"]=="Reda", 'color'] = "Red"
df
name age color flag
taro 11 Red TRUE
jiro 21 Blue TRUE
saburo 22 Green FALSE

# まとめ

Pandasの小技をまとめてました。(01)

# 参考サイト

分散分析とカイ二乗検定の違いについて

分散分析とカイ二乗検定の違いについて

BigQueryでST_INTERSECTSを使って苦労した話

BigQueryでST_INTERSECTSを使って苦労した話

BigQueryでST_INTERSECTSを使って苦労したことを綴ります。