データフレームの中がリストになってしまったり、区切りになってしまうことがある際に、それを別のカラムに分解する方法を備忘録的にまとめておきます。よかったら試してみてください。
データフレームの中がリスト→区切りに変換
import pandas as pd
df = pd.DataFrame(
{'col_1': [["A","B","C"],["D","E","F"],["G","H","I"]]},
index=[1, 2, 3])
df
![](https://i0.wp.com/nlab-notebook.com/wp-content/uploads/2023/10/image-7.png?resize=82%2C119&ssl=1)
#いったんリストをカンマ区切りに変更するための関数
#map関数を用いて全部の行に適用させる
def list_out(x):
return ','.join(x)
df["col_1"]=df["col_1"].map(list_out)
df
![](https://i0.wp.com/nlab-notebook.com/wp-content/uploads/2023/10/image-8.png?resize=71%2C117&ssl=1)
データフレームの中が区切り→別のカラムに分解する
expand=Trueを指定することで、分解することができます。(.str.は必須)
df['col_1'].str.split(',',expand=True)
![](https://i0.wp.com/nlab-notebook.com/wp-content/uploads/2023/10/image-9.png?resize=96%2C112&ssl=1)
”str.split(‘区切り文字(,や/など)’,expand=True)”を使うことで簡単に区切りから別のカラムに分解することができます。ぜひ使ってみてください。
(参考)別パターン
df = pd.DataFrame(
{'col_0':[1,2,3],
'col_1': [["A","B","C"],["D","E","F"],["G","H","I"]]},
index=[1, 2, 3])
df
![](https://i0.wp.com/nlab-notebook.com/wp-content/uploads/2023/10/image-11.png?resize=124%2C110&ssl=1)
上記のような場合を、リストの要素ごとで縦に分解するイメージのものが以下のコードになっています。
df.explode("col_1", ignore_index=False)
![](https://i0.wp.com/nlab-notebook.com/wp-content/uploads/2023/10/image-12.png?resize=117%2C272&ssl=1)
このような展開のやり方もありますので是非お試しを!!
コメント