データフレームの中がリストになってしまったり、区切りになってしまうことがある際に、それを別のカラムに分解する方法を備忘録的にまとめておきます。よかったら試してみてください。
データフレームの中がリスト→区切りに変換
import pandas as pd
df = pd.DataFrame(
{'col_1': [["A","B","C"],["D","E","F"],["G","H","I"]]},
index=[1, 2, 3])
df

#いったんリストをカンマ区切りに変更するための関数
#map関数を用いて全部の行に適用させる
def list_out(x):
return ','.join(x)
df["col_1"]=df["col_1"].map(list_out)
df

データフレームの中が区切り→別のカラムに分解する
expand=Trueを指定することで、分解することができます。(.str.は必須)
df['col_1'].str.split(',',expand=True)

”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

上記のような場合を、リストの要素ごとで縦に分解するイメージのものが以下のコードになっています。
df.explode("col_1", ignore_index=False)

このような展開のやり方もありますので是非お試しを!!
コメント