0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

カンマ区切りの文字列を含む1列のDataFrameの正規化

Last updated at Posted at 2025-05-28

はじめに

私はこういう持ち方のデータが大嫌いだ。無精してExcel上で「データの区切り位置」等でちまちまやろうとすると100億%事故るからである。1つのセルに複数の内容が入っているのが耐え難い。
しかし、現実においてはそうもいっていられないため、自分用のチートシート的に書いておく。

pandas.melt()を使う方法

import pandas as pd

# データの定義
data = {'hunter_list': [
    'gonn,kilua,leolio,klapika',
    'hisoka,menti,hanzo',
    'kaito'
]}

# データフレーム作成
df = pd.DataFrame(data)

# カンマで分割して複数列に展開
df_split = df['hunter_list'].str.split(',', expand=True)

# meltで縦一列に変換 → 重複・欠損を削除 → インデックスをリセット
df_melted = (
    df_split
    .melt(value_name='hunter')
    .dropna()
    .drop_duplicates(subset='hunter')
    .reset_index(drop=True)
)

# 結果表示
print(df_melted['hunter'])

出力

0       gonn
1     hisoka
2      kaito
3      kilua
4      menti
5     leolio
6      hanzo
7    klapika
Name: hunter, dtype: object

★ポイント
str.split(',', expand=True):カンマで分割して列に展開
melt():複数列を縦一列に変換
dropna():空のセルを削除
drop_duplicates():重複を削除
reset_index(drop=True):インデックスを振り直し

pandas.melt()を使わない方法

import pandas as pd

# データの定義
data = {'hunter_list': [
    'gonn,kilua,leolio,klapika',
    'hisoka,menti,hanzo',
    'kaito'
]}

# カンマで分割し、縦一列に並べる
flattened_list = [item.strip() for line in data['hunter_list'] for item in line.split(',')]

# pandasのSeriesに変換して処理
series = pd.Series(flattened_list)

# 空要素削除・重複削除・インデックス振り直し
cleaned_series = series.replace('', pd.NA).dropna().drop_duplicates().reset_index(drop=True)

# 結果を出力
print(cleaned_series)

出力

0       gonn
1      kilua
2     leolio
3    klapika
4     hisoka
5      menti
6      hanzo
7      kaito
dtype: object

感想

これまでpandas.melt()でずっとやっていたのだが、他の方法でも同じ処理ができることが分かって良かった。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?