LoginSignup
2
5

More than 3 years have passed since last update.

pandasで複数行ヘッダのCSVを出力する方法

Last updated at Posted at 2020-03-24

やりたいこと

以下のようなヘッダが複数行で構成されている表をCSVで出力したいです。

image.png

備忘録として記事を投稿いたします。

環境

  • Python 3.8.1
  • pandas 1.0.3

実現方法

  1. columnsがMultiIndexであるDataFrameを作成する
  2. DataFrameのto_csvメソッドで出力する

DataFrameの作成方法

DataFrameコンストラクタのdata引数にdictを渡す。

df = pandas.DataFrame({
    ("Alice","Math"): [80,81],
    ("Alice","English"): [90,91],
    ("Bob","Math"): [70,71]
})

print(df)
#   Alice          Bob
#    Math English Math
# 0    80      90   70
# 1    81      91   71

print(df.columns)
# MultiIndex([('Alice',    'Math'),
#             ('Alice', 'English'),
#             (  'Bob',    'Math')],
#            )

DataFrameコンストラクタのcolumns引数にMultiIndexを渡す

index = pandas.MultiIndex.from_tuples([
    ("Alice","Math"),
    ("Alice","English"),
    ("Bob","Math")
])

df2 = pandas.DataFrame([[80,90,70],[81,91,71]], columns=index)

print(df2)
#   Alice          Bob
#    Math English Math
# 0    80      90   70
# 1    81      91   71

print(df2.columns)
# MultiIndex([('Alice',    'Math'),
#             ('Alice', 'English'),
#             (  'Bob',    'Math')],
#            )

DataFrameコンストラクタのdata引数にdictのlistを渡す

コンストラクタ引数columnsがNoneだと、columnsプロパティの型がIndexになり、複数行ヘッダで出力できません。

df3 = pandas.DataFrame(
    [
        {("Alice","Math"):80, ("Alice","English"):90,("Bob","Math"):70},
        {("Alice","Math"):81, ("Alice","English"):91,("Bob","Math"):71},
    ]
)

print(df3)
#    (Alice, Math)  (Alice, English)  (Bob, Math)
# 0             80                90           70
# 1             81                91           71

print(df3.columns)
# Index([('Alice', 'Math'), ('Alice', 'English'), ('Bob', 'Math')], dtype='object')

columns引数にMultiIndexを渡せば、複数行ヘッダを出力できます。

index = pandas.MultiIndex.from_tuples([
    ("Alice","Math"),
    ("Alice","English"),
    ("Bob","Math")
])

df3 = pandas.DataFrame(
    [
        {("Alice","Math"):80, ("Alice","English"):90,("Bob","Math"):70},
        {("Alice","Math"):81, ("Alice","English"):91,("Bob","Math"):71},
    ]
    ,columns=index
)

print(df3)
#   Alice          Bob
#    Math English Math
# 0    80      90   70
# 1    81      91   71

DataFrameのto_csvメソッドで出力する

df.to_csv("foo.csv", index=False)
foo.csv
Alice,Alice,Bob
Math,English,Math
80,90,70
81,91,71
2
5
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
2
5