Skip to content

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

データフレームの作成

python
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)
nameagecolorflag
taro11RedTRUE
jiro21BlueTRUE
saburo22GreenFALSE

リストで複数条件で抽出

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

python
# リストで抽出
_list = ["taro", "jiro"]
df[df["name"].isin(_list)]
nameagecolorflag
taro11RedTRUE
jiro21BlueTRUE

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

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

python
# 文字列で特定の文字を含む
df[df["name"].str.contains("ro")]
nameagecolorflag
taro11RedTRUE
jiro21BlueTRUE
saburo22GreenFALSE

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

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

python
#  pandasでfor文を使わない処理(1列)
df["new_columns"] = df["name"].apply(lambda x: x + "_aaa")
display(df)
nameagecolorflagnew_columns
taro11RedTRUERed_aaa
jiro21BlueTRUEBlue_aaa
saburo22GreenFALSEGreen_aaa

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

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

python
#  pandasでfor文を使わない処理(2列)
df["new_columns"] = df[["name", "color"]].apply(lambda x: x[0] + x[1], axis=1)
display(df)
nameagecolorflagnew_columns
taro11RedTRUEtaroRed
jiro21BlueTRUEjiroBlue
saburo22GreenFALSEsaburoGreen

重複削除

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

python
#  重複削除
df.drop_duplicates(subset="flag")
nameagecolorflagnew_columns
taro11RedTRUEtaroRed
saburo22GreenFALSEsaburoGreen

カラム削除

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

python
# カラム削除
df.drop('new_columns', axis=1, inplace=True)
df
nameagecolorflag
taro11RedTRUE
jiro21BlueTRUE
saburo22GreenFALSE

置換

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

python
# 置換
df["color"] = df["color"].str.replace("Red", "Reda")
df
nameagecolorflag
taro11RedaTRUE
jiro21BlueTRUE
saburo22GreenFALSE

条件置換

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

python
# 条件置換
df.loc[df["color"]=="Reda", 'color'] = "Red"
df
nameagecolorflag
taro11RedTRUE
jiro21BlueTRUE
saburo22GreenFALSE

まとめ

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

参考サイト