一般社団法人 全国個人事業主支援協会

COLUMN コラム

meltによるReshaping

unstackより柔軟性がある縦持ち方法。早めに知っておきたかった。

cheese = pd.DataFrame(
   {
       "first": ["John", "Mary"],
        "last": ["Doe", "Bo"],
        "height": [5.5, 6.0],
        "weight": [130, 150],
    }
)

cheese

cheese.melt(id_vars=["first", "last"])

cheese.melt(id_vars=["first", "last"], var_name="quantity")

デフォルトではIndexは無視されるが、ignore_index=FalseでIndexを保持

index = pd.MultiIndex.from_tuples([("person", "A"), ("person", "B")])
cheese = pd.DataFrame(
    {
        "first": ["John", "Mary"],
        "last": ["Doe", "Bo"],
        "height": [5.5, 6.0],
        "weight": [130, 150],
    },
    index=index,
)
cheese

cheese.melt(id_vars=["first", "last"], ignore_index=False)

 

The following two tabs change content below.

WATANABE REN

千葉県在住のエンジニアです。最近はPythonやってます。

この記事をシェアする

  • Twitterでシェア
  • Facebookでシェア
  • LINEでシェア