3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pandasでカラム名がTupleになってしまうというバグ?を踏み抜いた件

Posted at

pandas使っていて奇妙な挙動を踏み抜いたので、その備忘録。
この状況になると、カラム名がstringではなくなぜかTupleになってしまいます。
pandas力が低いのでバグなのか、仕方ない挙動なのかは不明です。

今回踏み抜いた挙動

空のDataFrameに対してpivotをかけて、その結果のDataFrameにインデクサーアクセスで新しいカラムを追加するとColumnがTupleとして追加される

通常の挙動

import pandas as pd

empty_df = pd.DataFrame()
print("Plain1:", empty_df)
"""
ただの空のDataFrame
Plain1: Empty DataFrame
Columns: []
Index: []
"""
empty_df["new_column"] = 1
print("Plain2:",empty_df)
"""
# Printed
Plain2: Empty DataFrame
Columns: [new_column] # <- ちゃんとstring
Index: []
"""

今回踏み抜いたバグ?挙動

import pandas as pd

empty_df = pd.DataFrame(columns=["id","key"])
empty_df["value"] = 1 # ただのemptyなdfだと、pivotする時に例外が発生。これをすると何故かpivotが可能に
print("Pivot1:", empty_df)
"""
Pivot1: Empty DataFrame
Columns: [id, key, value]
Index: []
"""

pivot = pd.pivot_table(empty_df, index="id", columns="key", values="value")
print("Pivot1:", pivot)
"""
# ただの空のDataFrame
Pivot2: Empty DataFrame
Columns: []
Index: []
"""

pivot["new_column"] = 1
print("Pivot3:",pivot)
"""
# Printed
Pivot3: Empty DataFrame
Columns: [(new_column, )] # <- カラム名がなぜかTuple
Index: []
"""
3
1
1

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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?