<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Pandas集計・結合入門｜groupby, concat, mergeの基本と実践 | Python Data Lab（Pythonデータラボ）</title>
	<atom:link href="https://pythondatalab.com/category/pandas/aggregation/feed/" rel="self" type="application/rss+xml" />
	<link>https://pythondatalab.com</link>
	<description>Python初心者向けに、わかりやすいデータ分析の解説を提供します。</description>
	<lastBuildDate>Sun, 31 May 2026 13:14:08 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://pythondatalab.com/wp-content/uploads/2025/12/cropped-rogo-32x32.png</url>
	<title>Pandas集計・結合入門｜groupby, concat, mergeの基本と実践 | Python Data Lab（Pythonデータラボ）</title>
	<link>https://pythondatalab.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>pandas resample()の使い方｜日付データを月別・週別に集計する方法</title>
		<link>https://pythondatalab.com/pandas-resample/</link>
					<comments>https://pythondatalab.com/pandas-resample/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sun, 31 May 2026 13:12:33 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2082</guid>

					<description><![CDATA[<p>pandasのresample()で日付データを月別・週別・日別に集計する方法を初心者向けに解説。to_datetime()で日付型に変換し、set_index()やon引数を使って売上合計・件数・平均を集計する流れ、groupby()やasfreq()との違いも紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-resample/">pandas resample()の使い方｜日付データを月別・週別に集計する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
<div class="colab-article">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css">

<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-clike.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-python.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>

<style>
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers {
    margin: 0 !important;
    padding: 1em;
  }

  .colab-article pre.colab-output,
  .colab-article pre.colab-error {
    margin: 0 !important;
    padding: 0.8em 1em;
    overflow-x: auto;
    white-space: pre;
    background: #f7f7f7;
    border: 1px solid #d9d9d9;
  }

  .colab-article figure.wp-block-table {
    margin: 0.8em 0;
    overflow-x: auto;
  }

  .colab-article table.wp-block-table,
  .colab-article figure.wp-block-table table {
    width: auto;
    border-collapse: collapse;
  }

  .colab-article .colab-figure {
    margin: 1em 0;
  }

  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>


<p>CSVやExcelを読み込んだあと、注文日・来店日・売上日などの日付列はあるのに、次のような集計で迷うことがあります。</p>
<ul>
<li>月ごとの売上合計を出したい</li>
<li>週ごとの注文件数を数えたい</li>
<li>日別の平均売上を確認したい</li>
<li>集計した結果を折れ線グラフで見たい</li>
</ul>
<p>このようなときに役立つのが、pandasの <code>resample()</code> です。</p>
<p><code>resample()</code> は、日付データを日別・週別・月別などの時間単位でまとめて集計するためのメソッドです。</p>
<p>イメージとしては、1行ずつ並んでいる日付データを「1日ごと」「1週間ごと」「1か月ごと」の箱に分け、その箱ごとに合計・平均・件数を計算する処理です。</p>
<p>たとえば、1件ずつ並んでいる注文データから、月別売上や週別件数を作りたいときに使います。</p>
<p>この記事では、<code>to_datetime()</code> で日付列を整えるところから、<code>resample()</code> で月別・週別・日別に集計し、最後にグラフ化へつなげる流れまで、Google Colabで試しやすいサンプルデータを使って解説します。</p>



  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-1" checked><label class="toc-title" for="toc-checkbox-1">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">関連する前提知識</a></li><li><a href="#toc3" tabindex="0">まず結論：resample()は日付を時間単位でまとめるときに使う</a></li><li><a href="#toc4" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc5" tabindex="0">resample()を使う前に日付列をdatetime型にする</a></li><li><a href="#toc6" tabindex="0">方法1：日付列をインデックスにしてresample()する</a></li><li><a href="#toc7" tabindex="0">月別売上を集計する：resample(&#8220;MS&#8221;).sum()</a><ol><li><a href="#toc8" tabindex="0">出力例で見る：MS・ME・Mの違い</a></li></ol></li><li><a href="#toc9" tabindex="0">頻度指定の基本：D・W・MS・MEを使い分ける</a></li><li><a href="#toc10" tabindex="0">複数の集計をまとめて出す</a></li><li><a href="#toc11" tabindex="0">週別件数を集計する：resample(&#8220;W&#8221;).count()</a></li><li><a href="#toc12" tabindex="0">日別平均を集計する：resample(&#8220;D&#8221;).mean()</a></li><li><a href="#toc13" tabindex="0">方法2：on引数で日付列を指定してresample()する</a></li><li><a href="#toc14" tabindex="0">groupby()・dt・resample()の違い</a></li><li><a href="#toc15" tabindex="0">比較用：dtで年月列を作ってgroupby()する方法</a></li><li><a href="#toc16" tabindex="0">補足：resample()とasfreq()の違い</a></li><li><a href="#toc17" tabindex="0">集計結果をreset_index()で通常の表に戻す</a></li><li><a href="#toc18" tabindex="0">集計結果をグラフで確認する</a></li><li><a href="#toc19" tabindex="0">よくあるミスと確認ポイント</a><ol><li><a href="#toc20" tabindex="0">日付列がobject型のままになっている</a></li><li><a href="#toc21" tabindex="0">DatetimeIndexまたはonで指定した日付列が必要</a></li><li><a href="#toc22" tabindex="0">売上合計・平均・件数を混同しない</a></li><li><a href="#toc23" tabindex="0">月だけでgroupbyすると年をまたいだときに混ざる</a></li><li><a href="#toc24" tabindex="0">欠損期間が出ることがある</a></li></ol></li><li><a href="#toc25" tabindex="0">resample()はデータ分析の流れのどこで使うか</a></li><li><a href="#toc26" tabindex="0">まとめ</a></li><li><a href="#toc27" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc28" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc29" tabindex="0">resample()とgroupby()の違いは何ですか？</a></li><li><a href="#toc30" tabindex="0">resample()とasfreq()の違いは何ですか？</a></li><li><a href="#toc31" tabindex="0">resample()を使うには必ずset_index()が必要ですか？</a></li><li><a href="#toc32" tabindex="0">日付列がobject型のままだとresample()できますか？</a></li><li><a href="#toc33" tabindex="0">月別集計はresample()とdt.month＋groupby()のどちらがよいですか？</a></li><li><a href="#toc34" tabindex="0">resample(&#8220;M&#8221;)・resample(&#8220;ME&#8221;)・resample(&#8220;MS&#8221;)の違いは何ですか？</a></li><li><a href="#toc35" tabindex="0">resample()した後に普通の列に戻すにはどうすればよいですか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を学びます。</p>
<ul>
<li><code>resample()</code> が何をするメソッドか</li>
<li><code>resample()</code> を使う前に日付列を <code>datetime</code> 型にする理由</li>
<li><code>set_index()</code> してから <code>resample()</code> する基本</li>
<li><code>on="日付列"</code> で日付列を指定して集計する方法</li>
<li>日別・週別・月別に集計する方法</li>
<li><code>sum()</code>、<code>mean()</code>、<code>count()</code> の使い分け</li>
<li><code>groupby()</code>・<code>dt</code>・<code>resample()</code> の違い</li>
<li><code>resample()</code> と <code>asfreq()</code> の違い</li>
<li>集計結果を <code>reset_index()</code> で扱いやすい表に戻す方法</li>
<li>集計結果をグラフ化へつなげる流れ</li>
</ul>
<p>この記事のゴールは、<strong>日付列をdatetime型に整え、resample()で日別・週別・月別に集計し、集計結果を表やグラフで確認できるようになること</strong>です。</p>


<h2><span id="toc2">関連する前提知識</span></h2>
<p>この記事は、日付データを「時間のまとまり」で集計する記事です。</p>
<p>先に次の内容を確認しておくと、より理解しやすくなります。</p>
<ul>
<li><a href="https://pythondatalab.com/google-colab-csv/">Google ColabでCSVを読み込む方法｜Drive連携とpandas read_csvを初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換と format・NaT 対処を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-set-index/">pandas set_index()の使い方｜列をインデックスにする・drop=False・index_col・reset_indexとの違いを解説</a></li>
<li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
</ul>
<p>ただし、この記事では必要な部分を順番に確認するため、最初から読んでも進められるようにしています。</p>


<h2><span id="toc3">まず結論：resample()は日付を時間単位でまとめるときに使う</span></h2>
<p><code>resample()</code> は、日付データを一定の時間単位でまとめるために使います。</p>
<p>たとえば、次のような明細データがあるとします。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2600</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1800</td>
</tr>
</tbody>
</table></figure>
<p>このような1件ずつのデータを、次のように月別にまとめたいときに <code>resample()</code> が役立ちます。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">年月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上合計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
</tr>
</tbody>
</table></figure>
<p>ポイントは、<code>resample()</code> が「カテゴリごと」ではなく、<strong>日付を基準にして、日別・週別・月別などの時間のまとまりで集計する</strong>ことです。</p>
<p>最初に判断基準を整理すると、次のようになります。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使うもの</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日付を月別・週別・日別にまとめたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別売上、週別件数</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">カテゴリや店舗ごとにまとめたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>groupby()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">カテゴリ別売上、店舗別平均</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日付から年・月・曜日を取り出したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>dt</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">年列、月列、曜日列を追加</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">文字列の日付を日付型に変換したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>to_datetime()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"2026-01-05"</code> をdatetime型にする</td>
</tr>
</tbody>
</table></figure>
<p>この記事では、このうち <code>resample()</code> を中心に扱います。</p>


<h2><span id="toc4">サンプルデータを用意する</span></h2>
<p>ここでは、注文日・カテゴリ・商品・売上・数量を持つ小さな売上データを使います。</p>
<p>実際のCSVでは日付順に並んでいるとは限らないため、サンプルデータもあえて少し日付順をばらしています。</p>


<pre class="line-numbers"><code class="language-python">import pandas as pd

df = pd.DataFrame({
    "注文日": [
        "2026-03-15", "2026-01-05", "2026-02-03", "2026-01-18",
        "2026-03-28", "2026-02-25", "2026-01-28", "2026-02-12",
        "2026-03-02", "2026-01-12", "2026-02-05", "2026-03-05"
    ],
    "カテゴリ": [
        "食品", "食品", "日用品", "食品",
        "日用品", "食品", "日用品", "日用品",
        "食品", "日用品", "食品", "食品"
    ],
    "商品": [
        "コーヒー", "パン", "洗剤", "お茶",
        "ティッシュ", "お米", "歯ブラシ", "シャンプー",
        "牛乳", "ノート", "卵", "ヨーグルト"
    ],
    "売上": [1800, 1200, 2600, 1500, 900, 4200, 700, 3200, 1100, 600, 980, 1300],
    "数量": [3, 2, 1, 3, 2, 1, 2, 1, 2, 3, 2, 2]
})

display(df)
print(df.dtypes)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">数量</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">コーヒー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">パン</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">洗剤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お茶</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ティッシュ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">900</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-25</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お米</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">歯ブラシ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">700</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">シャンプー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">牛乳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ノート</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">卵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ヨーグルト</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
</tbody>
</table></figure>

<pre class="colab-output">注文日     object
カテゴリ    object
商品      object
売上       int64
数量       int64
dtype: object
</pre>

<p><code>注文日</code> は日付のように見えますが、この時点では <code>object</code> 型です。</p>
<p><code>resample()</code> で日付を基準に集計するには、日付列を <code>datetime</code> 型に変換する必要があります。</p>
<p>CSVやExcelを読み込んだ直後は、まず <code>dtypes</code> や <code>info()</code> で型を確認するのが大切です。</p>


<h2><span id="toc5">resample()を使う前に日付列をdatetime型にする</span></h2>
<p><code>注文日</code> を <code>pd.to_datetime()</code> で <code>datetime</code> 型に変換します。</p>
<p>ここでは、変換後に日付順で並び替えておきます。<br>
日付順に並んでいなくても集計自体はできますが、表示や確認がしやすくなります。</p>


<pre class="line-numbers"><code class="language-python">df_date = df.copy()

df_date["注文日"] = pd.to_datetime(df_date["注文日"])
df_date = df_date.sort_values("注文日")

display(df_date)
print(df_date.dtypes)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">数量</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">パン</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ノート</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お茶</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">歯ブラシ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">700</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">洗剤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">卵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">シャンプー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-25</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お米</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">牛乳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ヨーグルト</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">コーヒー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ティッシュ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">900</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
</tbody>
</table></figure>

<pre class="colab-output">注文日     datetime64[ns]
カテゴリ            object
商品              object
売上               int64
数量               int64
dtype: object
</pre>

<p><code>注文日</code> の型が <code>datetime64[ns]</code> になりました。</p>
<p>これで、pandasがこの列を「日付として扱える状態」になりました。</p>
<p>日付変換そのものを詳しく知りたい場合は、<a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方</a>で、<code>format</code> や <code>NaT</code> の考え方を確認できます。</p>


<h2><span id="toc6">方法1：日付列をインデックスにしてresample()する</span></h2>
<p><code>resample()</code> の基本は、日付列をインデックスにしてから集計する書き方です。</p>
<p>ここでは、<code>set_index("注文日")</code> で <code>注文日</code> をインデックスにします。</p>


<pre class="line-numbers"><code class="language-python">df_time = df_date.set_index("注文日")

display(df_time)
print(type(df_time.index))
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">数量</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">パン</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ノート</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お茶</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">歯ブラシ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">700</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">洗剤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2600</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">卵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">シャンプー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-25</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">お米</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">牛乳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ヨーグルト</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">食品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">コーヒー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日用品</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">ティッシュ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">900</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
</tbody>
</table></figure>

<pre class="colab-output">&lt;class 'pandas.core.indexes.datetimes.DatetimeIndex'&gt;
</pre>

<p><code>注文日</code> がインデックスになり、<code>DatetimeIndex</code> として扱われるようになりました。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">状態</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日の位置</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">resample()での扱いやすさ</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">処理前</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">通常の列</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">そのままでは基本形のresample()に使いにくい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">処理後</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">DatetimeIndex</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>df.resample("MS")</code> のように集計できる</td>
</tr>
</tbody>
</table></figure>
<p><code>set_index()</code> の詳しい使い方は、<a href="https://pythondatalab.com/pandas-set-index/">pandas set_index()の使い方</a>で確認できます。</p>


<h2><span id="toc7">月別売上を集計する：resample(&#8220;MS&#8221;).sum()</span></h2>
<p>まずは、月別の売上合計を出します。</p>
<p>ここでは <code>resample("MS")</code> を使います。</p>
<ul>
<li><code>MS</code> は、月初基準の月別集計です</li>
<li><code>ME</code> は、月末基準の月別集計です</li>
<li>古い記事では <code>M</code> と書かれていることがありますが、最近のpandasでは月末基準を表すなら <code>ME</code> を使う方が安全です</li>
<li><code>sum()</code> は、売上を合計するために使います</li>
</ul>
<p>「月別売上を知りたい」場合は、平均ではなく合計を出すことが多いため、ここでは <code>sum()</code> を使います。</p>
<p>この記事では、月ごとの結果を表で見たときに読みやすいように、月初の日付で表示される <code>MS</code> を中心に使います。</p>


<pre class="line-numbers"><code class="language-python">monthly_sales = df_time.resample("MS")["売上"].sum().to_frame("月別売上合計")

display(monthly_sales)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">月別売上合計</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
</tr>
</tbody>
</table></figure>

<p>1件ずつ並んでいた明細データが、月ごとの売上合計にまとまりました。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">処理前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">処理後</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">注文日ごとに1行ずつ並んだ明細データ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月ごとに売上を合計した集計表</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">売上の推移が見えにくい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026年1月、2月、3月の売上合計を比較しやすい</td>
</tr>
</tbody>
</table></figure>
<p>このように、<code>resample()</code> は時系列データを「見やすい単位」にまとめるときに役立ちます。</p>


<h3><span id="toc8">出力例で見る：MS・ME・Mの違い</span></h3>
<p><code>MS</code> と <code>ME</code> の違いは、集計結果の「ラベル日付」に出ます。</p>
<ul>
<li><code>MS</code>：月初の日付で表示されます</li>
<li><code>ME</code>：月末の日付で表示されます</li>
<li><code>M</code>：古い記事や古いコードで見かける月末基準の書き方です</li>
</ul>
<p>売上合計の金額は同じでも、表示される日付ラベルが変わる点を確認してみましょう。</p>


<pre class="line-numbers"><code class="language-python">monthly_ms = df_time.resample("MS")["売上"].sum().reset_index()
monthly_ms.columns = ["MSのラベル日付", "MSの売上合計"]

monthly_me = df_time.resample("ME")["売上"].sum().reset_index()
monthly_me.columns = ["MEのラベル日付", "MEの売上合計"]

# 古い記事では resample("M") を見かけることがあります。
# 最近のpandasでは月末基準を表す場合、resample("ME") を使う方が安全です。
try:
    import warnings

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", FutureWarning)
        monthly_m = df_time.resample("M")["売上"].sum().reset_index()

    monthly_m.columns = ["Mのラベル日付", "Mの売上合計"]
    display(pd.concat([monthly_ms, monthly_me, monthly_m], axis=1))

except Exception:
    print("このpandas環境では resample('M') を実行できません。月末基準は resample('ME') を使ってください。")
    display(pd.concat([monthly_ms, monthly_me], axis=1))
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">MSのラベル日付</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">MSの売上合計</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">MEのラベル日付</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">MEの売上合計</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">Mのラベル日付</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">Mの売上合計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
</tr>
</tbody>
</table></figure>

<p><code>MS</code> は <code>2026-01-01</code>、<code>2026-02-01</code> のように月初の日付で表示されます。</p>
<p>一方、<code>ME</code> は <code>2026-01-31</code>、<code>2026-02-28</code> のように月末の日付で表示されます。</p>
<p>古い記事で見かける <code>M</code> は、月末基準の古い書き方として出てくることがあります。新しく記事を書く場合や、これから学ぶ場合は、月末基準なら <code>ME</code>、月初基準なら <code>MS</code> と覚えておくと混乱しにくいです。</p>


<h2><span id="toc9">頻度指定の基本：D・W・MS・MEを使い分ける</span></h2>
<p><code>resample()</code> のカッコの中には、どの時間単位でまとめるかを指定します。</p>
<p>初心者のうちは、まず次の指定を覚えれば十分です。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">指定</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">意味</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使う場面</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"D"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日別</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日ごとの平均・件数を見たい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"W"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">週別</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">週ごとの注文件数や売上を見たい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"MS"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別（月初基準）</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別集計を月初の日付で表示したい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"ME"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別（月末基準）</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別集計を月末の日付で表示したい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"M"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別（月末基準の古い書き方）</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">古い記事や古いコードで見かけることがある</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"QE"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">四半期</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">四半期ごとに軽くまとめたい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>"YE"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">年別</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">年ごとに軽くまとめたい</td>
</tr>
</tbody>
</table></figure>
<p>検索すると、月別集計の例で <code>resample("M")</code> を見かけることがあります。
ただし、最近のpandasでは <code>M</code> よりも、月末基準なら <code>ME</code>、月初基準なら <code>MS</code> と書く方がわかりやすく、今後も安心です。</p>
<p>この記事では、月別の表として見やすいように、主に <code>"MS"</code> を使います。</p>


<h2><span id="toc10">複数の集計をまとめて出す</span></h2>
<p>月別に、売上合計・注文件数・平均売上・数量合計をまとめて出すこともできます。</p>
<p>ここでは、次のように集計します。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">出したい値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使う集計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">売上合計</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>sum()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">注文件数</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>count()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">平均売上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>mean()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">数量合計</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>sum()</code></td>
</tr>
</tbody>
</table></figure>
<p>売上合計と平均売上は意味が違います。<br>
また、<code>count()</code> は指定した列の欠損値を数えません。今回のように <code>売上</code> 列に欠損がない前提なら注文件数として使えますが、行数そのものを数えたい場合は <code>size()</code> も候補になります。<br>
見出しや表の名前と、実際に使う集計方法がズレないように注意しましょう。</p>


<pre class="line-numbers"><code class="language-python">monthly_summary = df_time.resample("MS").agg(
    売上合計=("売上", "sum"),
    注文件数=("売上", "count"),
    平均売上=("売上", "mean"),
    数量合計=("数量", "sum")
)

display(monthly_summary)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上合計</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文件数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">平均売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">数量合計</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2745.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1275.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">9</td>
</tr>
</tbody>
</table></figure>

<p>この表を見ると、月ごとの売上合計だけでなく、注文件数や平均売上も確認できます。</p>
<p>実務では、売上合計だけを見ると「2月が大きい」とわかります。<br>
さらに注文件数や平均売上を見ると、「件数が多いのか、1件あたりの売上が大きいのか」も確認しやすくなります。</p>


<h2><span id="toc11">週別件数を集計する：resample(&#8220;W&#8221;).count()</span></h2>
<p>次に、週ごとの注文件数を数えてみます。</p>
<p>ここでは「売上の合計」ではなく、「何件の注文があったか」を見たいので、<code>count()</code> を使います。今回のサンプルでは <code>売上</code> 列に欠損がないため、<code>売上</code> を数えることで注文件数を確認できます。</p>


<pre class="line-numbers"><code class="language-python">weekly_count = df_time.resample("W")["売上"].count().to_frame("週別注文件数")

display(weekly_count)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">週別注文件数</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-25</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-08</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-22</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-08</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-22</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
</tr>
</tbody>
</table></figure>

<p><code>W</code> は週別の集計です。</p>
<p>週別集計では、週の区切り方によって結果の見え方が変わることがあります。<br>
初心者のうちは、まず「週ごとにざっくり件数を見る」用途で使い、細かい週の開始日・終了日の指定は必要になったときに確認すれば十分です。</p>


<h2><span id="toc12">日別平均を集計する：resample(&#8220;D&#8221;).mean()</span></h2>
<p>次に、日別の平均売上を確認します。</p>
<p>ここでは <code>resample("D")</code> で日別にまとめ、<code>mean()</code> で平均を出します。</p>


<pre class="line-numbers"><code class="language-python">daily_mean = df_time.resample("D")["売上"].mean().to_frame("日別平均売上")

display(daily_mean.head(10))
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">日別平均売上</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200.0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-06</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-07</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-08</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-09</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600.0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-13</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-14</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
</tr>
</tbody>
</table></figure>

<p>日別にすると、注文がない日も期間として表示されることがあります。</p>
<p>この例では、注文がない日の平均売上は <code>NaN</code> になります。<br>
これはエラーではなく、「その日に集計できるデータがなかった」という意味です。</p>
<p>欠損期間の補完や <code>ffill()</code>、<code>interpolate()</code> などの処理は便利ですが、この記事では深入りしません。<br>
まずは、<code>resample()</code> によって空の期間が見えることがある、と理解しておきましょう。</p>


<h2><span id="toc13">方法2：on引数で日付列を指定してresample()する</span></h2>
<p><code>resample()</code> は、必ず <code>set_index()</code> しないと使えないわけではありません。</p>
<p>日付列が <code>datetime</code> 型になっていれば、<code>on="注文日"</code> のように指定して集計できます。</p>
<p>インデックスを変更したくない場合は、この書き方が便利です。</p>


<pre class="line-numbers"><code class="language-python">monthly_sales_on = (
    df_date
    .resample("MS", on="注文日")["売上"]
    .sum()
    .reset_index(name="月別売上合計")
)

display(monthly_sales_on)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">月別売上合計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
</tr>
</tbody>
</table></figure>

<p><code>on="注文日"</code> を使うと、<code>注文日</code> をインデックスにしなくても月別集計ができます。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">書き方</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">特徴</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>set_index("注文日").resample("MS")</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">時系列データとして扱う流れがわかりやすい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample("MS", on="注文日")</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">インデックスを変えずに日付列を指定できる</td>
</tr>
</tbody>
</table></figure>
<p>初心者の学習では、まず <code>set_index()</code> する基本形を理解し、慣れてきたら <code>on</code> 引数を使うとよいです。</p>


<h2><span id="toc14">groupby()・dt・resample()の違い</span></h2>
<p>日付データを扱うときは、<code>groupby()</code>、<code>dt</code>、<code>resample()</code> の違いで迷いやすいです。</p>
<p>ここで一度、使い分けを整理します。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使うもの</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">役割</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日付を日別・週別・月別などの時間単位で集計する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別売上、週別件数</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>groupby()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">カテゴリや作成した列ごとに集計する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">カテゴリ別売上、店舗別平均</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>dt</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日付から年・月・曜日などを取り出す</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月列を作る、曜日列を作る</td>
</tr>
</tbody>
</table></figure>
<p>月別集計は、<code>dt.month</code> で月列を作って <code>groupby()</code> する方法でもできます。<br>
ただし、年をまたぐデータで「月」だけを使うと、2025年1月と2026年1月が混ざる可能性があります。</p>
<p>日付の流れに沿って月別・週別にまとめたい場合は、<code>resample()</code> を使うと自然です。</p>


<h2><span id="toc15">比較用：dtで年月列を作ってgroupby()する方法</span></h2>
<p>比較のために、<code>dt.to_period("M")</code> で年月列を作り、<code>groupby()</code> で月別集計する例も確認します。</p>
<p>これは <code>resample()</code> の代わりに使える場面もありますが、この記事ではあくまで違いを理解するための補足です。</p>


<pre class="line-numbers"><code class="language-python">df_group = df_date.copy()

df_group["年月"] = df_group["注文日"].dt.to_period("M")

monthly_groupby = (
    df_group
    .groupby("年月")["売上"]
    .sum()
    .reset_index(name="月別売上合計")
)

display(monthly_groupby)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">年月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">月別売上合計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
</tr>
</tbody>
</table></figure>

<p><code>dt</code> と <code>groupby()</code> を組み合わせても月別集計はできます。</p>
<p>ただし、今回のように「日付を時間単位でまとめる」ことが目的なら、<code>resample()</code> を使うと、日別・週別・月別への切り替えがしやすくなります。</p>
<p><code>dt</code> の詳しい使い方は <a href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方</a> で、カテゴリ別集計は <a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方</a> で確認できます。</p>


<h2><span id="toc16">補足：resample()とasfreq()の違い</span></h2>
<p>時系列データの記事では、<code>resample()</code> と一緒に <code>asfreq()</code> というメソッドを見かけることがあります。</p>
<p>初心者のうちは、まず次のように分けて考えると十分です。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使うもの</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">考え方</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">月別売上の合計を出したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample().sum()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">期間ごとに集計する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">週別の平均を出したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample().mean()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">期間ごとに集計する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">日付の間隔だけそろえたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>asfreq()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">指定した頻度の行を作る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">欠けている日付を表示したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>asfreq()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">集計せず、日付の並びをそろえる</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">欠けた期間も含めて集計結果を確認したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>resample()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">期間の箱を作って集計する</td>
</tr>
</tbody>
</table></figure>
<p><code>resample()</code> は、日付を一定期間の箱に分けて、その箱ごとに合計・平均・件数などを計算します。</p>
<p>一方、<code>asfreq()</code> は、日付の頻度をそろえるための処理です。基本的には集計をするメソッドではありません。</p>
<p>この記事では、月別売上や週別件数のように「期間ごとに集計する」ことが目的なので、主役は <code>resample()</code> です。ここでは、<code>asfreq()</code> が集計ではなく日付の間隔をそろえる処理であることを、短いコードで確認します。</p>


<pre class="line-numbers"><code class="language-python">daily_asfreq = df_time["売上"].asfreq("D").to_frame("asfreq_D")
daily_resample_sum = df_time["売上"].resample("D").sum().to_frame("resample_D_sum")

daily_compare = pd.concat([daily_asfreq, daily_resample_sum], axis=1)

display(daily_compare.head(10))
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">asfreq_D</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">resample_D_sum</th>
</tr>

</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1200</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-06</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-07</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-08</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-09</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">600</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-13</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-14</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
</tr>
</tbody>
</table></figure>

<p>上の表を見ると、<code>asfreq("D")</code> は日付の間隔を日別にそろえるだけなので、注文がない日は <code>NaN</code> になります。</p>
<p>一方、<code>resample("D").sum()</code> は日別の箱を作って売上を合計するため、注文がない日は合計が0のように表示されることがあります。</p>
<p>つまり、<strong>集計したいなら <code>resample()</code>、日付の並びをそろえたいなら <code>asfreq()</code></strong> と考えると分かりやすいです。</p>


<h2><span id="toc17">集計結果をreset_index()で通常の表に戻す</span></h2>
<p><code>resample()</code> の結果は、日付がインデックスになっていることが多いです。</p>
<p>このままでも分析できますが、CSVに保存したり、他の表と結合したり、WordPress記事で表として見せたりする場合は、<code>reset_index()</code> で通常の列に戻すと扱いやすくなります。</p>


<pre class="line-numbers"><code class="language-python">monthly_summary_reset = monthly_summary.reset_index()

monthly_summary_reset["年月"] = monthly_summary_reset["注文日"].dt.strftime("%Y-%m")

display(monthly_summary_reset)
</code></pre>

<figure class="wp-block-table"><table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">売上合計</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">注文件数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">平均売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">数量合計</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">年月</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-01</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">10980</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2745.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-02</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">5100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">1275.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">2026-03</td>
</tr>
</tbody>
</table></figure>

<p><code>reset_index()</code> によって、インデックスだった <code>注文日</code> が通常の列に戻りました。</p>
<p>さらに <code>strftime("%Y-%m")</code> を使うと、<code>2026-01</code> のような年月表示も作れます。</p>
<p><code>reset_index()</code> の詳しい使い方は、<a href="https://pythondatalab.com/pandas-reset-index/">pandas reset_index()の使い方</a>で確認できます。</p>


<h2><span id="toc18">集計結果をグラフで確認する</span></h2>
<p>月別集計ができたら、折れ線グラフや棒グラフにすると推移を確認しやすくなります。</p>
<p>ここでは、月別売上合計を簡単な折れ線グラフで表示します。<br>
グラフ装飾は深入りせず、集計結果を可視化につなげる流れだけ確認します。</p>
<p>なお、Google Colabでは日本語フォント設定をしていないと、グラフ内の日本語ラベルが文字化けすることがあります。ここでは、まず <code>resample()</code> の集計結果を確認することを優先し、グラフのタイトルや軸ラベルは英語表記にしています。</p>
<p>ここでは月別の集計結果を折れ線グラフにします。日付ラベルが重ならないように、x軸の表示を<code>YYYY-MM</code>形式にし、ラベルを少し回転させています。</p>


<pre class="line-numbers"><code class="language-python">import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plot_df = monthly_summary_reset.copy()

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(plot_df["注文日"], plot_df["売上合計"], marker="o")

ax.set_title("Monthly Sales")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.grid(True)

# x軸の日付ラベルが重ならないように、表示形式と角度を調整します
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
plt.xticks(rotation=45, ha="right")
plt.tight_layout()

plt.show()
</code></pre>

<figure class="colab-figure">
  <img decoding="async" src="images/figure1.png" alt="グラフの出力画像1">
  <figcaption>グラフの出力画像1</figcaption>
</figure>

<p>このように、<code>resample()</code> で月別に集計すると、売上の推移をグラフで確認しやすくなります。</p>
<p>折れ線グラフの設定を詳しく知りたい場合は、<a href="https://pythondatalab.com/matplotlib-line-legend-color/">Matplotlib折れ線グラフの描き方</a>を参考にしてください。<br>
月別売上を棒グラフで比較したい場合は、<a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a>も役立ちます。</p>


<h2><span id="toc19">よくあるミスと確認ポイント</span></h2>
<p><code>resample()</code> でつまずきやすいポイントを整理します。</p>
<h3><span id="toc20">日付列がobject型のままになっている</span></h3>
<p>日付に見えても、<code>object</code> 型のままだと <code>resample()</code> でうまく扱えません。</p>
<p>まず <code>pd.to_datetime()</code> で日付型に変換しましょう。</p>
<h3><span id="toc21">DatetimeIndexまたはonで指定した日付列が必要</span></h3>
<p><code>resample()</code> は、日付列そのものを自動で探してくれるわけではありません。</p>
<p>基本形では、日付列をインデックスにします。<br>
インデックスにしたくない場合は、<code>on="注文日"</code> のように指定します。</p>
<h3><span id="toc22">売上合計・平均・件数を混同しない</span></h3>
<p><code>sum()</code>、<code>mean()</code>、<code>count()</code> は意味が違います。</p>
<figure class="wp-block-table"><table class="wp-block-table" style="width: auto; border-collapse: collapse; margin: 0.8em 0;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">見たいもの</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9; font-weight: 600; background: #f7f7f7;">使う集計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">売上合計</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>sum()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">平均売上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>mean()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;">注文件数</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #d9d9d9;"><code>count()</code> または <code>size()</code></td>
</tr>
</tbody>
</table></figure>
<p><code>count()</code> は、指定した列の欠損値を数えません。欠損を含む列で件数を数える場合は、<code>count()</code> と <code>size()</code> の違いに注意します。</p>
<p>「月別売上を集計する」という見出しなら <code>sum()</code>、<br>
「平均を出す」という見出しなら <code>mean()</code> を使うように、説明とコードを一致させることが大切です。</p>
<h3><span id="toc23">月だけでgroupbyすると年をまたいだときに混ざる</span></h3>
<p><code>dt.month</code> だけで集計すると、2025年1月と2026年1月が同じ「1月」としてまとまる可能性があります。</p>
<p>年をまたぐデータでは、<code>dt.to_period("M")</code> を使うか、<code>resample()</code> で年月を意識した集計にする方が安全です。</p>
<h3><span id="toc24">欠損期間が出ることがある</span></h3>
<p>日別や週別で集計すると、データがない期間が表示されることがあります。<br>
平均なら <code>NaN</code>、合計なら0のように見える場合があります。</p>
<p>これは、<code>resample()</code> が時間の区切りを作って集計しているためです。</p>


<h2><span id="toc25">resample()はデータ分析の流れのどこで使うか</span></h2>
<p><code>resample()</code> は、データ分析の流れの中では「日付を使った集計」の場面で使います。</p>
<p>全体の流れで見ると、次の位置づけです。</p>
<ol>
<li>CSVやExcelを読み込む</li>
<li><code>head()</code> や <code>info()</code> でデータを確認する</li>
<li><code>to_datetime()</code> で日付列を日付型にする</li>
<li>必要に応じて <code>sort_values()</code> で日付順に並べる</li>
<li><code>resample()</code> で日別・週別・月別に集計する</li>
<li><code>reset_index()</code> で表として扱いやすくする</li>
<li>Matplotlibで推移を可視化する</li>
</ol>
<p>つまり、<code>resample()</code> は、単独で覚えるよりも、<strong>日付変換・集計・可視化へ進む流れの中で覚える</strong>と使いやすくなります。</p>
<p>なお、移動平均を出す <code>rolling()</code> や、頻度をそろえる <code>asfreq()</code> も時系列データで使われます。<br>
ただし、この記事では <code>resample()</code> の基本に集中するため、詳しい使い方は別記事で扱う範囲です。</p>


<h2><span id="toc26">まとめ</span></h2>
<p>この記事では、pandasの <code>resample()</code> を使って、日付データを月別・週別・日別に集計する方法を解説しました。</p>
<p>重要なポイントは次のとおりです。</p>
<ul>
<li><code>resample()</code> は、日付データを日別・週別・月別などの時間単位で集計するために使う</li>
<li>使う前に、日付列を <code>pd.to_datetime()</code> で <code>datetime</code> 型に変換する</li>
<li>基本形では、<code>set_index("日付列")</code> で日付をインデックスにしてから <code>resample()</code> する</li>
<li>インデックスを変えたくない場合は、<code>on="日付列"</code> を使える</li>
<li>月別売上なら <code>sum()</code>、平均売上なら <code>mean()</code>、件数なら <code>count()</code> を使う</li>
<li>カテゴリ別にまとめたいなら <code>groupby()</code>、年・月・曜日を取り出したいなら <code>dt</code>、時間単位でまとめたいなら <code>resample()</code> を使う</li>
<li>集計結果は <code>reset_index()</code> で通常の表に戻すと扱いやすい</li>
<li>月別集計の結果は、折れ線グラフや棒グラフにすると推移を確認しやすい</li>
</ul>
<p><code>resample()</code> を使えるようになると、CSVやExcelで読み込んだ日付付きデータから、月別売上・週別件数・日別平均などを作れるようになります。</p>
<p>日付データを前処理して、集計し、可視化する流れの中で、とても役立つメソッドです。</p>


<h2><span id="toc27">次に読みたい関連記事</span></h2>
<p>日付集計をさらに理解するには、次の記事も参考になります。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換と format・NaT 対処を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-set-index/">pandas set_index()の使い方｜列をインデックスにする・drop=False・index_col・reset_indexとの違いを解説</a></li>
<li><a href="https://pythondatalab.com/pandas-reset-index/">pandas reset_index()の使い方｜インデックスを振り直す・drop=Trueを初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
<li><a href="https://pythondatalab.com/pandas-sort/">pandas 並び替え（sort）入門｜sort_values・sort_indexの違いと複数列ソート</a></li>
<li><a href="https://pythondatalab.com/matplotlib-line-legend-color/">Matplotlib折れ線グラフの描き方：色・線種・凡例を完全解説</a></li>
<li><a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門：横棒・グループ化・積み上げまで解説</a></li>
<li><a href="https://pythondatalab.com/google-colab-csv/">Google ColabでCSVを読み込む方法｜Drive連携とpandas read_csvを初心者向けに解説</a></li>
</ul>

<!-- ▼▼▼ カテゴリから探す　 共通スタイル（カテゴリ）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc28"> カテゴリから探す</span></h3> <ul>
<ul>
<li><a href="https://pythondatalab.com/category/pandas/basic/">◀ Pandas 基礎</a></li>
<li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ Pandas 抽出・前処理</a></li>
<li><a href="https://pythondatalab.com/category/pandas/aggregation/">◀ Pandas 集計・変形</a></li>
<li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ Matplotlib　可視化</a></li> </ul> </ul></div>
<!-- ▼▼▼ カテゴリから探す　共通スタイル（カテゴリ）終了▼▼▼ -->
<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>



<script>Prism.highlightAll();</script>

</div>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1780219709616" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc29">resample()とgroupby()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>resample()</code> は、日付を日別・週別・月別などの時間単位でまとめるときに使います。<br />一方、<code>groupby()</code> は、カテゴリ・店舗・商品など、列の値ごとにまとめるときに使います。<br />月別売上や週別件数のように、時間の区切りで集計したい場合は <code>resample()</code> が向いています。<br />カテゴリ別売上や店舗別平均のように、分類ごとに集計したい場合は <code>groupby()</code> が向いています。</p>

</div>
</div>
<div id="faq-question-1780219745235" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">resample()とasfreq()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code><br />resample()</code> は、日付を一定期間ごとにまとめて、合計・平均・件数などを計算するために使います。<br />一方、<code>asfreq()</code> は、日付の間隔をそろえるために使います。基本的には集計をするメソッドではありません。<br />たとえば、注文がない日を日付として表示したいだけなら <code>asfreq()</code>、日ごとの売上合計を出したいなら <code>resample("D").sum()</code> を使います。<br />月別売上や週別件数を出したい場合は <code>resample()</code>、日付の並びをそろえたい場合は <code>asfreq()</code> と考えると分かりやすいです。</p>

</div>
</div>
<div id="faq-question-1780219757098" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">resample()を使うには必ずset_index()が必要ですか？</span></h3>
<div class="rank-math-answer ">

<p>必ずではありません。<br />基本形では、日付列を <code>set_index()</code> でインデックスにしてから <code>resample()</code> します。<br />ただし、日付列が <code>datetime</code> 型になっていれば、<code>resample("MS", on="注文日")</code> のように <code>on</code> 引数で日付列を指定することもできます。</p>

</div>
</div>
<div id="faq-question-1780219770722" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">日付列がobject型のままだとresample()できますか？</span></h3>
<div class="rank-math-answer ">

<p>基本的には、日付列は <code>datetime</code> 型に変換してから使います。<br />日付に見える文字列でも、pandas上では <code>object</code> 型になっていることがあります。<br />その場合は、先に <code>pd.to_datetime()</code> で変換しましょう。</p>

</div>
</div>
<div id="faq-question-1780219787554" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">月別集計はresample()とdt.month＋groupby()のどちらがよいですか？</span></h3>
<div class="rank-math-answer ">

<p>日付の流れに沿って月別・週別・日別に集計したい場合は、<code>resample()</code> が自然です。<br /><code>dt.month</code> で月だけを取り出して <code>groupby()</code> する方法もありますが、年をまたぐデータでは、2025年1月と2026年1月が混ざる可能性があります。<br />年も含めて集計したい場合は、<code>dt.to_period("M")</code> を使うか、<code>resample()</code> を使うと安全です。</p>

</div>
</div>
<div id="faq-question-1780219802554" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">resample(&#8220;M&#8221;)・resample(&#8220;ME&#8221;)・resample(&#8220;MS&#8221;)の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>MS</code> は月初基準、<code>ME</code> は月末基準の月別集計です。<br />たとえば、1月の集計結果を <code>2026-01-01</code> のような月初日付で表示したい場合は <code>MS</code>、<code>2026-01-31</code> のような月末日付で表示したい場合は <code>ME</code> を使います。<br />古い記事や古いコードでは <code>resample("M")</code> を見かけることがあります。これは月末基準の古い書き方として出てくることがありますが、最近のpandasでは <code>ME</code> と書く方が安全です。<br />初心者向けの記事や表では、月初基準の <code>MS</code> の方が月ごとのまとまりを読み取りやすいことがあります。</p>

</div>
</div>
<div id="faq-question-1780219831290" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">resample()した後に普通の列に戻すにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p><code>reset_index()</code> を使います。<br /><code>resample()</code> の結果は、日付がインデックスになっていることがあります。<br />CSVに保存したり、他のDataFrameと結合したり、表として見せたりする場合は、<code>reset_index()</code> で日付を通常の列に戻すと扱いやすくなります。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-resample/">pandas resample()の使い方｜日付データを月別・週別に集計する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-resample/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas crosstab()の使い方｜2つの列をクロス集計・割合表示する方法</title>
		<link>https://pythondatalab.com/pandas-crosstab/</link>
					<comments>https://pythondatalab.com/pandas-crosstab/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sun, 10 May 2026 15:41:24 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2072</guid>

					<description><![CDATA[<p>pandasのcrosstab()を使って、2つの列の組み合わせをクロス集計する方法を初心者向けに解説。value_counts()との違い、合計行・合計列、normalizeによる割合表示、欠損値の注意点までわかります。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-crosstab/">pandas crosstab()の使い方｜2つの列をクロス集計・割合表示する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[

<div class="colab-article">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css">

<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-clike.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-python.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>

<style>
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers {
    margin: 0 !important;
    padding: 1em !important;
  }
  .colab-article code {
    font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 0.8em 0 1.2em 0;
    display: block;
    overflow-x: auto;
    max-width: 100%;
  }
  .colab-article table.wp-block-table th,
  .colab-article table.wp-block-table td {
    border: 1px solid #ddd;
  }
  .colab-article .colab-output {
    margin: 0.8em 0 1.2em 0 !important;
    padding: 0.8em !important;
    background: #f6f8fa;
    overflow-x: auto;
  }
  .colab-article figure.colab-figure {
    margin: 1em 0;
  }
  .colab-article figure.colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>


<p>CSVを読み込んだあと、「地域ごとに購入あり・購入なしの件数を見たい」「年代ごとに満足度の分布を確認したい」と思うことがあります。</p>
<p>このように、<strong>2つの列の組み合わせごとの件数を表で見たい</strong>ときに便利なのが、pandasの <code>crosstab()</code> です。</p>
<p><code>crosstab()</code> を使うと、たとえば「地域×購入有無」「年代×満足度」のようなクロス集計表を短いコードで作れます。</p>
<p>基本形は次のとおりです。</p>
<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;行にしたい列&quot;], df[&quot;列にしたい列&quot;])
</code></pre>
<p>この記事では、pandasの <code>crosstab()</code> を使って、2つの列を組み合わせたクロス集計表を作る方法を解説します。あわせて、<code>value_counts()</code>、<code>groupby()</code>、<code>pivot_table()</code> との違い、割合表示、合計行・合計列も整理します。</p>



  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2" checked><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">crosstab()が役立つ場面</a></li><li><a href="#toc3" tabindex="0">サンプルデータを作成する</a></li><li><a href="#toc4" tabindex="0">1列だけならvalue_counts()で確認する</a></li><li><a href="#toc5" tabindex="0">2つの列を組み合わせたクロス集計表を作る</a><ol><li><a href="#toc6" tabindex="0">地域×購入有無を集計する</a></li><li><a href="#toc7" tabindex="0">行と列を入れ替えると見え方が変わる</a></li><li><a href="#toc8" tabindex="0">年代×満足度を集計する</a></li></ol></li><li><a href="#toc9" tabindex="0">合計行・合計列を追加する</a></li><li><a href="#toc10" tabindex="0">件数を割合で表示する</a><ol><li><a href="#toc11" tabindex="0">全体に対する割合を見る</a></li><li><a href="#toc12" tabindex="0">行ごとの割合を見る</a></li><li><a href="#toc13" tabindex="0">列ごとの割合を見る</a></li><li><a href="#toc14" tabindex="0">小数を見やすく丸める</a></li></ol></li><li><a href="#toc15" tabindex="0">欠損値があるときの注意点</a></li><li><a href="#toc16" tabindex="0">実務では、件数表から割合表示につなげる</a></li><li><a href="#toc17" tabindex="0">まとめ</a></li><li><a href="#toc18" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc19" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc20" tabindex="0">value_counts()ではなくcrosstab()を使うのはどんなときですか？</a></li><li><a href="#toc21" tabindex="0">crosstab()で売上合計や平均値も出せますか？</a></li><li><a href="#toc22" tabindex="0">pivot_table()ではなくcrosstab()を使うのはどんなときですか？</a></li><li><a href="#toc23" tabindex="0">crosstab()で割合を表示できますか？</a></li><li><a href="#toc24" tabindex="0">crosstab()で合計行や合計列を追加できますか？</a></li><li><a href="#toc25" tabindex="0">valuesやaggfuncも使う必要がありますか？</a></li><li><a href="#toc26" tabindex="0">欠損値がある場合、crosstab()の結果はどうなりますか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、<code>crosstab()</code> で2つの列の組み合わせを集計する方法を学びます。</p>
<p>具体的には、次の内容を扱います。</p>
<ul>
<li><code>pd.crosstab()</code> の基本的な使い方</li>
<li>1列だけを見る <code>value_counts()</code> との違い</li>
<li>2つの列を組み合わせたクロス集計表の作り方</li>
<li>合計行・合計列を追加する方法</li>
<li>件数を割合で表示する方法</li>
<li>欠損値があるときの注意点</li>
<li><code>crosstab()</code> が役立つ実践的な場面</li>
</ul>
<p><code>crosstab()</code> は、<code>value_counts()</code> で1列の件数を確認したあとに、<strong>2つの列の関係を表で見たいとき</strong>に使うメソッドです。</p>


<h2><span id="toc2">crosstab()が役立つ場面</span></h2>
<p><code>crosstab()</code> は、2つの列の組み合わせごとの件数を見たい場面で役立ちます。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
  <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">場面</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">見たい組み合わせ</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">購入データの確認</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">地域 × 購入有無</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">アンケート分析</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">年代 × 満足度</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A/Bテストの確認</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">パターンA/B × 申込有無</td>
</tr>
</tbody>
</table>
<p>この記事では、まず <code>地域×購入有無</code> と <code>年代×満足度</code> の例で、基本的なクロス集計を確認します。</p>


<h2><span id="toc3">サンプルデータを作成する</span></h2>
<p>ここでは、地域・年代・商品カテゴリ・購入有無・満足度を含む小さなデータを使います。</p>
<p>実務ではCSVから読み込むことが多いですが、この記事ではGoogle Colabでそのまま試せるように、DataFrameを直接作成します。</p>


<pre class="line-numbers"><code class="language-python">
import pandas as pd

df = pd.DataFrame({
    &quot;地域&quot;: [&quot;東京&quot;, &quot;東京&quot;, &quot;東京&quot;, &quot;大阪&quot;, &quot;大阪&quot;, &quot;大阪&quot;, &quot;名古屋&quot;, &quot;名古屋&quot;, &quot;福岡&quot;, None],
    &quot;年代&quot;: [&quot;20代&quot;, &quot;20代&quot;, &quot;30代&quot;, &quot;40代&quot;, &quot;40代&quot;, &quot;30代&quot;, &quot;20代&quot;, &quot;30代&quot;, &quot;40代&quot;, &quot;30代&quot;],
    &quot;商品カテゴリ&quot;: [&quot;PC&quot;, &quot;PC&quot;, &quot;文房具&quot;, &quot;家具&quot;, &quot;家具&quot;, &quot;文房具&quot;, &quot;PC&quot;, &quot;文房具&quot;, &quot;家具&quot;, &quot;PC&quot;],
    &quot;購入有無&quot;: [&quot;購入あり&quot;, &quot;購入あり&quot;, &quot;購入あり&quot;, &quot;購入なし&quot;, &quot;購入なし&quot;, &quot;購入なし&quot;, &quot;購入あり&quot;, &quot;購入なし&quot;, &quot;購入なし&quot;, &quot;購入あり&quot;],
    &quot;満足度&quot;: [&quot;高い&quot;, &quot;高い&quot;, &quot;普通&quot;, &quot;低い&quot;, &quot;低い&quot;, &quot;普通&quot;, &quot;高い&quot;, &quot;普通&quot;, &quot;低い&quot;, None]
})

df
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">地域</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">年代</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">商品カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入有無</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">満足度</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">高い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">高い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">文房具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">普通</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">家具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">低い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">家具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">低い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">文房具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">普通</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">高い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">文房具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">普通</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">家具</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">低い</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">None</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">None</td>
    </tr>
  </tbody>
</table>

<p>このデータでは、クロス集計後の傾向が見えやすいように、次のような特徴を入れています。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
  <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">列名</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">使いどころ</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">地域</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京は購入ありが多く、大阪は購入なしが多い例に使う</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">年代</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">20代は満足度が高く、40代は低い例に使う</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品カテゴリ</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">カテゴリ列の例として使う</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">購入有無</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">地域ごとの購入状況を比較する</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">満足度</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">年代ごとの満足度分布を比較する</td>
</tr>
</tbody>
</table>
<p><code>地域</code> と <code>満足度</code> には、あえて欠損値も入れています。<br />
あとで、欠損値がある場合の注意点も確認します。</p>


<h2><span id="toc4">1列だけならvalue_counts()で確認する</span></h2>
<p><code>crosstab()</code> は2つの列の組み合わせを見る方法です。</p>
<p>一方、1つの列だけの件数を見たい場合は、<code>value_counts()</code> のほうが簡単です。</p>
<p>まずは、<code>地域</code> 列だけの件数を確認してみます。</p>


<pre class="line-numbers"><code class="language-python">
df[&quot;地域&quot;].value_counts()
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">count</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>

<p><code>value_counts()</code> では、地域ごとの件数を確認できます。</p>
<p>ただし、これだけでは「地域ごとに購入あり・購入なしが何件あるか」は見えません。</p>
<p><strong>1列だけを見るなら <code>value_counts()</code>、2つの列の組み合わせを見るなら <code>crosstab()</code></strong> と考えるとわかりやすいです。</p>


<h2><span id="toc5">2つの列を組み合わせたクロス集計表を作る</span></h2>
<p>ここからは、<code>pd.crosstab()</code> を使って実際にクロス集計表を作ります。</p>
<p>まずは、<code>地域</code> と <code>購入有無</code> を指定して、地域ごとの購入状況を集計します。</p>
<h3><span id="toc6">地域×購入有無を集計する</span></h3>
<p>「地域ごとに、購入あり・購入なしが何件あるか」を確認する例です。</p>


<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;])
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>

<p>この結果を見ると、行に <code>地域</code>、列に <code>購入有無</code> が並びます。</p>
<p>たとえば、このサンプルデータでは、東京は「購入あり」が多く、大阪は「購入なし」が多いことがわかります。</p>
<p><code>crosstab()</code> は元のDataFrameを書き換える処理ではなく、集計結果として新しい表を作る処理です。</p>


<h3><span id="toc7">行と列を入れ替えると見え方が変わる</span></h3>
<p><code>crosstab()</code> では、最初に指定した列が行、2つ目に指定した列が列になります。</p>
<p>次のコードでは、先ほどとは逆に、<code>購入有無</code> を行、<code>地域</code> を列に置いてみます。</p>


<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;購入有無&quot;], df[&quot;地域&quot;])
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">東京</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">購入なし</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>

<p>集計している内容は同じでも、<code>pd.crosstab()</code> に指定する列の順番を変えると、行と列が入れ替わります。</p>
<p>初心者のうちは、「比較したいグループ」を1つ目の引数、つまり行側に置くと読みやすくなります。</p>


<h3><span id="toc8">年代×満足度を集計する</span></h3>
<p>同じ考え方で、<code>年代</code> と <code>満足度</code> の組み合わせも集計できます。</p>
<p>これは、アンケート集計のように「年代ごとに、満足度がどのように分布しているか」を確認する例です。</p>


<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;年代&quot;], df[&quot;満足度&quot;])
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">低い</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">普通</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">高い</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
  </tbody>
</table>

<p>この表では、年代ごとに「高い」「普通」「低い」が何件あるかを確認できます。</p>
<p>このサンプルデータでは、20代は「高い」が多く、40代は「低い」が多いことがわかります。</p>
<p>このように、単に満足度全体の件数を見るだけでなく、年代別に分けると傾向が見えやすくなります。<br />
<code>crosstab()</code> は、アンケート集計の入口としても使いやすい方法です。</p>


<h2><span id="toc9">合計行・合計列を追加する</span></h2>
<p>クロス集計表では、行ごとの合計や列ごとの合計も見たいことがあります。</p>
<p>その場合は、<code>margins=True</code> を指定します。</p>


<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], margins=True)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">All</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">All</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">9</td>
    </tr>
  </tbody>
</table>

<p><code>margins=True</code> を使うと、合計行・合計列が追加されます。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
  <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">指定</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">意味</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>margins=True</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">行方向・列方向の合計を追加する</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>All</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">合計を表す行または列</td>
</tr>
</tbody>
</table>
<p>全体の件数も同時に確認したいときに便利です。</p>


<h2><span id="toc10">件数を割合で表示する</span></h2>
<p>件数だけでなく、割合で見たい場合は <code>normalize</code> を使います。</p>
<p><code>normalize</code> は、<strong>何を分母にして割合を出すか</strong>を指定する引数です。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
  <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">指定</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">意味</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">使う場面</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>normalize=True</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">全体に対する割合</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">全体の中でどれくらいかを見たい</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>normalize=&quot;index&quot;</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">行ごとの割合</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">地域ごとの購入有無の割合を見たい</td>
</tr>
<tr>
  <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>normalize=&quot;columns&quot;</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列ごとの割合</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入有無ごとの地域構成を見たい</td>
</tr>
</tbody>
</table>
<h3><span id="toc11">全体に対する割合を見る</span></h3>
<p>まずは、全体に対する割合を見てみます。</p>


<pre class="line-numbers"><code class="language-python">
# 全体に対する割合を表示する
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], normalize=True)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.1111111111111111</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.1111111111111111</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.3333333333333333</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.3333333333333333</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.1111111111111111</td>
    </tr>
  </tbody>
</table>

<p>この表では、全体を1として、それぞれの組み合わせがどれくらいの割合かを表しています。</p>
<p>実務でよく使うのは、次の <code>normalize=&quot;index&quot;</code> です。<br />
たとえば、地域ごとに「購入あり」「購入なし」の割合を見たいときに使います。</p>


<h3><span id="toc12">行ごとの割合を見る</span></h3>
<p><code>normalize=&quot;index&quot;</code> は、行ごとの合計を1として割合を出します。</p>
<p>次の例では、地域ごとに「購入あり」「購入なし」の割合を確認します。</p>


<pre class="line-numbers"><code class="language-python">
# 行ごとの割合を表示する
# ここでは「地域ごとに、購入あり・購入なしの割合」を見る
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], normalize=&quot;index&quot;)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.5</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
    </tr>
  </tbody>
</table>

<p>この表では、各地域の中で「購入あり」「購入なし」がどれくらいの割合かを確認できます。</p>
<p><code>normalize=&quot;index&quot;</code> は、<strong>行ごとの割合</strong>です。<br />
「年代ごとの満足度割合」を見たい場合も同じ考え方で使えます。</p>


<pre class="line-numbers"><code class="language-python">
# 行ごとの割合を表示する
# ここでは「年代ごとに、満足度の割合」を見る
pd.crosstab(df[&quot;年代&quot;], df[&quot;満足度&quot;], normalize=&quot;index&quot;)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">低い</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">普通</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">高い</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
  </tbody>
</table>

<p>このコードでは、年代ごとに満足度の割合を見ています。</p>
<p>「20代の中では高いが何割か」「30代の中では普通が何割か」のように、行ごとの分布を確認できます。</p>


<h3><span id="toc13">列ごとの割合を見る</span></h3>
<p><code>normalize=&quot;columns&quot;</code> は、列ごとの合計を1として割合を出します。</p>
<p>次の例では、購入あり・購入なしごとに、地域の構成を確認します。</p>


<pre class="line-numbers"><code class="language-python">
# 列ごとの割合を表示する
# ここでは「購入あり・購入なしごとに、地域の割合」を見る
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], normalize=&quot;columns&quot;)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.25</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.2</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.6</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.75</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.2</td>
    </tr>
  </tbody>
</table>

<p>この表では、列ごとの合計が1になります。</p>
<p><code>normalize=True</code>、<code>normalize=&quot;index&quot;</code>、<code>normalize=&quot;columns&quot;</code> は、分母が違います。<br />
割合を見るときは、「何を1としているのか」を必ず確認しましょう。</p>


<h3><span id="toc14">小数を見やすく丸める</span></h3>
<p>割合表示では、小数が長く表示されることがあります。</p>
<p>最初は割合の意味を理解することが大切ですが、表として見やすくしたい場合は <code>.round()</code> を使うと便利です。</p>


<pre class="line-numbers"><code class="language-python">
# 行ごとの割合を、小数第2位まで表示する
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], normalize=&quot;index&quot;).round(2)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.5</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.0</td>
    </tr>
  </tbody>
</table>

<p>この例では、小数第2位まで表示しています。</p>
<p>パーセント表記に整える方法もありますが、この記事では深入りしません。<br />
まずは、<code>normalize</code> の種類によって分母が変わることを理解しておきましょう。</p>


<h2><span id="toc15">欠損値があるときの注意点</span></h2>
<p><code>crosstab()</code> で使う列に欠損値があると、その行は集計表に入らない場合があります。</p>
<p>まずは、どの列に欠損値があるかを確認します。</p>


<pre class="line-numbers"><code class="language-python">
df.isnull().sum()
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">地域</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">年代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品カテゴリ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">購入有無</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">満足度</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>

<p>今回のデータでは、<code>地域</code> と <code>満足度</code> に欠損値があります。</p>
<p>ここでは、<code>地域</code> が欠損している行を確認してみます。</p>


<pre class="line-numbers"><code class="language-python">
df[df[&quot;地域&quot;].isnull()]
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">地域</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">年代</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">商品カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入有無</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">満足度</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">None</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">None</td>
    </tr>
  </tbody>
</table>

<p>元データは10行あります。</p>


<pre class="line-numbers"><code class="language-python">
len(df)
</code></pre>

<pre class="colab-output"><code>10</code></pre>

<p>次に、<code>地域×購入有無</code> のクロス集計表に合計行・合計列を付けて確認します。</p>


<pre class="line-numbers"><code class="language-python">
pd.crosstab(df[&quot;地域&quot;], df[&quot;購入有無&quot;], margins=True)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">All</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">All</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">9</td>
    </tr>
  </tbody>
</table>

<p>クロス集計表の合計は9件です。</p>
<p>元データは10行ありますが、<code>地域</code> が欠損している行は、東京・大阪・名古屋・福岡のどこにも分類できません。</p>
<p>そのため、<code>地域×購入有無</code> のクロス集計表には入らず、合計が9件になります。</p>
<p>このように、<code>crosstab()</code> で使う列に欠損値があると、集計表の合計件数が元データの行数より少なく見えることがあります。</p>


<p>欠損値を「未回答」として集計したい場合は、<code>fillna()</code> で置き換えてから <code>crosstab()</code> を使います。</p>


<pre class="line-numbers"><code class="language-python">
df_filled = df.copy()
df_filled[&quot;地域&quot;] = df_filled[&quot;地域&quot;].fillna(&quot;未回答&quot;)
df_filled[&quot;満足度&quot;] = df_filled[&quot;満足度&quot;].fillna(&quot;未回答&quot;)

pd.crosstab(df_filled[&quot;地域&quot;], df_filled[&quot;購入有無&quot;], margins=True)
</code></pre>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入あり</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">購入なし</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">All</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">未回答</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">All</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
    </tr>
  </tbody>
</table>

<p>ここでは、欠損値を「未回答」として扱いました。</p>
<p>ただし、欠損値をすべて機械的に埋めればよいわけではありません。<br />
未回答なのか、入力漏れなのか、分析対象外なのかを考えてから処理しましょう。</p>


<h2><span id="toc16">実務では、件数表から割合表示につなげる</span></h2>
<p><code>crosstab()</code> は、件数表を作って終わりではなく、合計や割合を確認すると傾向が見えやすくなります。</p>
<p>基本の流れは、次のとおりです。</p>
<ol>
<li><code>value_counts()</code> で1列の件数を確認する</li>
<li><code>crosstab()</code> で2つの列の組み合わせを集計する</li>
<li><code>margins=True</code> で合計を見る</li>
<li><code>normalize</code> で割合を見る</li>
</ol>
<p>まずは、<strong>件数表を作る → 合計を見る → 割合を見る</strong> の順番で確認すると、結果を読み取りやすくなります。</p>


<h2><span id="toc17">まとめ</span></h2>
<p>この記事では、pandasの <code>crosstab()</code> を使って、2つの列を組み合わせたクロス集計表を作る方法を解説しました。</p>
<p>ポイントを整理します。</p>
<ul>
<li><code>crosstab()</code> は、2つの列の組み合わせを件数表にしたいときに使う</li>
<li>1列の件数確認なら <code>value_counts()</code> が向いている</li>
<li>2列の組み合わせを見るなら <code>crosstab()</code> がわかりやすい</li>
<li>数値列の合計や平均を出したい場合は、<code>groupby()</code> や <code>pivot_table()</code> が向いている</li>
<li><code>margins=True</code> で合計行・合計列を追加できる</li>
<li><code>normalize</code> を使うと、件数を割合で表示できる</li>
<li><code>normalize=True</code>、<code>normalize=&quot;index&quot;</code>、<code>normalize=&quot;columns&quot;</code> は分母が違う</li>
<li>欠損値がある場合は、集計前に <code>isnull()</code> で確認すると安全</li>
</ul>
<p>なお、<code>values</code> や <code>aggfunc</code> を使う発展的な集計もありますが、初心者はまず「2つの列の件数表を作る」基本形を押さえれば十分です。</p>
<p><code>crosstab()</code> を使えるようになると、単に1列の件数を見るだけでなく、2つの列の関係を表で確認できるようになります。</p>
<p>「地域×購入有無」「年代×満足度」など、2つの列の組み合わせを表で確認できるため、<code>value_counts()</code> の次に覚えておきたいメソッドです。</p>


<h2><span id="toc18">次に読みたい関連記事</span></h2>
<p><code>crosstab()</code> を理解したら、次の記事に進むと、データ分析の流れがつながりやすくなります。</p>
<ul>
<li><p><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a><br />
1列の件数集計を復習したい場合におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a><br />
カテゴリ別に売上合計や平均を出したい場合に役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-pivot/">Pandas pivotとpivot_tableの違い｜重複データ対応と集計方法</a><br />
表の形を変えながら、より柔軟に集計したい場合におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-melt/">pandas melt()の使い方｜横持ちデータを縦持ちに変換する方法</a><br />
集計しやすい縦長データに整える方法を学べます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-isnull/">欠損値を可視化して攻略！Pandas isnullとヒートマップ活用術</a><br />
集計前に欠損値を確認したい場合におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a><br />
欠損値をどう扱うかを学びたい場合に役立ちます。</p>
</li>
</ul>


<!-- ▼▼▼ カテゴリから探す　 共通スタイル（カテゴリ）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc19"> カテゴリから探す</span></h3> <ul>
<ul>
<li><a href="https://pythondatalab.com/category/pandas/basic/">◀ Pandas 基礎</a></li>
<li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ Pandas 抽出・前処理</a></li>
<li><a href="https://pythondatalab.com/category/pandas/aggregation/">◀ Pandas 集計・変形</a></li>
<li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ Matplotlib　可視化</a></li> </ul> </ul></div>
<!-- ▼▼▼ カテゴリから探す　共通スタイル（カテゴリ）終了▼▼▼ -->
<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>
<script>Prism.highlightAll();</script>

</div>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1778426486348" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc20">value_counts()ではなくcrosstab()を使うのはどんなときですか？</span></h3>
<div class="rank-math-answer ">

<p><code>value_counts()</code> は、1つの列の値を数えるときに使います。<br />一方、<code>crosstab()</code> は、2つの列の組み合わせごとの件数を表にするときに使います。<br />たとえば、地域ごとの件数だけなら <code>value_counts()</code>、地域ごとの購入あり・購入なしを見たいなら <code>crosstab()</code> が向いています。</p>

</div>
</div>
<div id="faq-question-1778426494178" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc21">crosstab()で売上合計や平均値も出せますか？</span></h3>
<div class="rank-math-answer ">

<p>2つの列の件数表を作りたいなら <code>crosstab()</code> がわかりやすいです。<br />一方、カテゴリ別に売上合計や平均値などの数値を集計したい場合は、<code>groupby()</code> が向いています。</p>

</div>
</div>
<div id="faq-question-1778426506834" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc22">pivot_table()ではなくcrosstab()を使うのはどんなときですか？</span></h3>
<div class="rank-math-answer ">

<p><code>crosstab()</code> は、2つの列の組み合わせを件数表にする用途で使いやすい方法です。<br /><code>pivot_table()</code> は、行・列・値・集計方法を指定して、より柔軟な集計表を作る方法です。<br />初心者はまず、2つの列の件数表なら <code>crosstab()</code>、数値列を使った集計なら <code>pivot_table()</code> と分けて考えると理解しやすいです。</p>

</div>
</div>
<div id="faq-question-1778426520610" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc23">crosstab()で割合を表示できますか？</span></h3>
<div class="rank-math-answer ">

<p>できます。<br /><code>normalize=True</code>、<code>normalize="index"</code>、<code>normalize="columns"</code> を使うと、件数ではなく割合で表示できます。<br />・<code>normalize=True</code>：全体に対する割合<br /><code>・normalize="index"</code>：行ごとの割合<br /><code>・normalize="columns"</code>：列ごとの割合</p>

</div>
</div>
<div id="faq-question-1778426535394" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc24">crosstab()で合計行や合計列を追加できますか？</span></h3>
<div class="rank-math-answer ">

<p>できます。<br /><code>margins=True</code> を指定すると、合計行・合計列を追加できます。<br /><code>pd.crosstab(df["地域"], df["購入有無"], margins=True)</code></p>

</div>
</div>
<div id="faq-question-1778426566242" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc25">valuesやaggfuncも使う必要がありますか？</span></h3>
<div class="rank-math-answer ">

<p>初心者のうちは、まず <code>pd.crosstab(df["行にしたい列"], df["列にしたい列"])</code> の基本形を押さえれば十分です。<br /><code>values</code> や <code>aggfunc</code> を使うと、件数ではなく数値を集計することもできます。<br />ただし、売上合計や平均値のような数値集計を本格的に行う場合は、<code>groupby()</code> や <code>pivot_table()</code> とあわせて学ぶほうが理解しやすいです。</p>

</div>
</div>
<div id="faq-question-1778426586058" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">欠損値がある場合、crosstab()の結果はどうなりますか？</span></h3>
<div class="rank-math-answer ">

<p>欠損値がある行は、集計表に含まれない場合があります。<br />そのため、集計前に <code>df.isnull().sum()</code> で欠損値を確認しておくと安全です。<br />欠損値を「未回答」などのカテゴリとして扱いたい場合は、<code>fillna()</code> で置き換えてから <code>crosstab()</code> を使います。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-crosstab/">pandas crosstab()の使い方｜2つの列をクロス集計・割合表示する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-crosstab/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas melt()の使い方｜横持ちデータを縦持ちに変換する方法</title>
		<link>https://pythondatalab.com/pandas-melt/</link>
					<comments>https://pythondatalab.com/pandas-melt/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Mon, 04 May 2026 14:51:44 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2029</guid>

					<description><![CDATA[<p>pandasのmelt()で横持ちデータを縦持ちデータに変換する方法を解説。id_vars、value_varsの違いや、集計・グラフ化しやすい形に整える流れを初心者向けに紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-melt/">pandas melt()の使い方｜横持ちデータを縦持ちに変換する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[

<div class="colab-article">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css">
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-clike.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-python.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
<style>
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers {
    margin: 0 !important;
    padding: 1em;
  }
  .colab-article .colab-output {
    margin: 0.5em 0 1em;
    padding: 0.8em 1em;
    background: #f6f8fa;
    border: 1px solid #e5e7eb;
    overflow-x: auto;
    white-space: pre;
  }
  .colab-article .colab-table-wrap {
    overflow-x: auto;
    margin: 1em 0;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
  }
  .colab-article .colab-figure {
    margin: 1.2em 0;
    text-align: center;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
  .colab-article .colab-figure figcaption {
    font-size: 0.9em;
    color: #666;
    margin-top: 0.4em;
  }
</style>

<p>CSVを読み込んだあと、月別の売上や科目別の点数が横に並んでいて、集計しにくいと感じることがあります。</p>
<p>たとえば、次のような表です。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">1月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">2月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">3月</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
</tbody>
</table></div>
<p>このような表は、人間が見るにはわかりやすいです。</p>
<p>しかし、Pandasで月ごとに集計したり、グラフ化したりする場合は、次のように「月」と「売上」を列として持つ形のほうが扱いやすくなります。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
</tbody>
</table></div>
<p>このように、横に広がった列を縦長にまとめるときに使うのが、Pandasの <code>melt()</code> です。</p>
<p>この記事では、<code>melt()</code> の基本、<code>id_vars</code> と <code>value_vars</code> の使い分け、<code>groupby()</code> やグラフ化へつなげる流れを、初心者向けに順番に解説します。</p>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-3" checked><label class="toc-title" for="toc-checkbox-3">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">melt()はどんな場面で使うのか</a></li><li><a href="#toc3" tabindex="0">横持ちデータと縦持ちデータの違い</a><ol><li><a href="#toc4" tabindex="0">図解：横に並んだ月別列を縦にまとめる</a></li></ol></li><li><a href="#toc5" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc6" tabindex="0">基本形：melt()で横持ちを縦持ちに変換する</a><ol><li><a href="#toc7" tabindex="0">melt()は3つに分けて考えると迷いにくい</a></li></ol></li><li><a href="#toc8" tabindex="0">melt()後に行数が増える理由</a></li><li><a href="#toc9" tabindex="0">補足：元のindexを残したいときはignore_index=False</a></li><li><a href="#toc10" tabindex="0">id_varsの意味：そのまま残す列</a></li><li><a href="#toc11" tabindex="0">value_varsの意味：縦にまとめる列</a></li><li><a href="#toc12" tabindex="0">var_nameとvalue_nameで列名をわかりやすくする</a><ol><li><a href="#toc13" tabindex="0">value_nameは既存の列名と重ならない名前にする</a></li></ol></li><li><a href="#toc14" tabindex="0">value_varsを省略した場合の注意点</a><ol><li><a href="#toc15" tabindex="0">value_varsを省略すると不要な列まで入る例</a></li></ol></li><li><a href="#toc16" tabindex="0">科目別点数データでもmelt()を使う</a></li><li><a href="#toc17" tabindex="0">melt()した後にgroupby()で集計する</a></li><li><a href="#toc18" tabindex="0">melt()した後にvalue_counts()で件数を確認する</a></li><li><a href="#toc19" tabindex="0">melt()した後に棒グラフで可視化する</a><ol><li><a href="#toc20" tabindex="0">補足：Colabでグラフの日本語ラベルが文字化けするとき</a></li></ol></li><li><a href="#toc21" tabindex="0">melt()とpivot()・pivot_table()の違い</a></li><li><a href="#toc22" tabindex="0">melt()とconcat()・merge()の違い</a></li><li><a href="#toc23" tabindex="0">melt()と他のメソッドを迷ったときの使い分け</a></li><li><a href="#toc24" tabindex="0">よくあるミスと注意点</a></li><li><a href="#toc25" tabindex="0">前処理の流れの中でmelt()を使うタイミング</a><ol><li><a href="#toc26" tabindex="0">補足：CSVで読み込んだデータにもmelt()は使える</a></li></ol></li><li><a href="#toc27" tabindex="0">軽く知っておきたい関連メソッド</a></li><li><a href="#toc28" tabindex="0">まとめ</a></li><li><a href="#toc29" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc30" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc31" tabindex="0">pandas melt()は何をするメソッドですか？</a></li><li><a href="#toc32" tabindex="0">melt()はどんなときに使いますか？</a></li><li><a href="#toc33" tabindex="0">id_varsとvalue_varsの違いは何ですか？</a></li><li><a href="#toc34" tabindex="0">value_varsを省略してもよいですか？</a></li><li><a href="#toc35" tabindex="0">variable列とvalue列は何を意味しますか？</a></li><li><a href="#toc36" tabindex="0">melt()後に行数が増えるのはなぜですか？</a></li><li><a href="#toc37" tabindex="0">melt()とpivot()の違いは何ですか？</a></li><li><a href="#toc38" tabindex="0">melt()したあとにgroupby()やグラフ化はできますか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">この記事でわかること</span></h2>
<ul>
<li><code>melt()</code> が何をするメソッドか</li>
<li>横持ちデータと縦持ちデータの違い</li>
<li><code>id_vars</code> と <code>value_vars</code> の使い分け</li>
<li><code>var_name</code> と <code>value_name</code> で列名を整える方法</li>
<li><code>melt()</code> 後に行数が増える理由</li>
<li><code>value_vars</code> を省略するときの注意点</li>
<li><code>melt()</code> 後に <code>groupby()</code> や棒グラフへつなげる流れ</li>
</ul>
<p>この記事のゴールは、横に広がったDataFrameを、集計・可視化しやすい縦持ちデータに変換できるようになることです。</p>
<p>発展的な内容や環境差が出やすい内容は、本文の後半で補足として扱います。</p>

<h2><span id="toc2">melt()はどんな場面で使うのか</span></h2>
<p><code>melt()</code> は、次のように「同じ種類の情報が複数の列に分かれている」ときに役立ちます。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">データの例</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">横に並んでいる列</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">melt後に作りたい列</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月別売上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code>, <code>売上</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">科目別点数</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>国語</code>, <code>数学</code>, <code>英語</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>科目</code>, <code>点数</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品別数量</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>ノートPC</code>, <code>マウス</code>, <code>キーボード</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>商品</code>, <code>数量</code></td>
</tr>
</tbody>
</table></div>
<p>横持ちデータは人間が見る表としては便利です。</p>
<p>一方で、Pandasで集計・条件抽出・グラフ化をする場合は、項目名と値が列として分かれている縦持ちデータのほうが扱いやすいことがあります。</p>
<p>迷ったときは、次のように判断すると整理しやすいです。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">状況</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">melt()を使う？</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">理由</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code> のように同じ種類の列が横に並んでいる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code> 列と <code>売上</code> 列にまとめると集計しやすい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>国語</code>, <code>数学</code>, <code>英語</code> のように科目が列になっている</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>科目</code> 列と <code>点数</code> 列にまとめられる</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">すでに <code>月</code> 列と <code>売上</code> 列がある</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使わない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">すでに縦持ちなので変換不要</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">表として見やすく表示したいだけ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">無理に使わない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横持ちのほうが見やすい場合もある</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">列名を変えたいだけ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使わない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>rename()</code> のほうが目的に合う</td>
</tr>
</tbody>
</table></div>
<p>つまり、<code>melt()</code> は「横に並んだ同じ種類の列を、1つの項目列と1つの値列にまとめたい」ときに使います。</p>

<h2><span id="toc3">横持ちデータと縦持ちデータの違い</span></h2>
<p><code>melt()</code> を理解するには、まず横持ちデータと縦持ちデータの違いを押さえるとわかりやすいです。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">形式</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">特徴</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">向いている場面</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横持ちデータ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月・科目・商品などが列として横に並ぶ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">表として眺める、比較表として見る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦持ちデータ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月・科目・商品などを1つの列にまとめる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">集計、条件抽出、グラフ化</td>
</tr>
</tbody>
</table></div>
<p><code>melt()</code> は、横持ちデータを縦持ちデータに変換するためのメソッドです。</p>
<p>ポイントは、<strong>列名として横に並んでいた情報を、1つの列の値として縦に並べ直すこと</strong>です。</p>

<h3><span id="toc4">図解：横に並んだ月別列を縦にまとめる</span></h3>
<p><figure class="colab-figure"><img decoding="async" alt="pandas melt()で横持ちデータを縦持ちデータに変換する図解" loading="lazy" src="https://pythondatalab.com/wp-content/uploads/2026/05/melt_wide_to_long_diagram.png"/><figcaption>pandas melt()で横持ちデータを縦持ちデータに変換する図解</figcaption></figure></p>
<p>図のように、<code>1月</code>、<code>2月</code>、<code>3月</code> のように横に並んだ列を、<code>月</code> 列と <code>売上</code> 列にまとめます。</p>
<p>このとき、<code>社員名</code> のように残したい列は <code>id_vars</code> に指定します。</p>
<p>一方で、<code>1月</code>、<code>2月</code>、<code>3月</code> のように縦へまとめたい列は <code>value_vars</code> に指定します。</p>
<p><code>melt()</code> は売上を合計する処理ではありません。集計やグラフ化をしやすい形に並べ直す前処理です。</p>

<h2><span id="toc5">サンプルデータを用意する</span></h2>
<p>ここでは、社員ごとの月別売上データを使います。</p>
<p><code>1月</code>、<code>2月</code>、<code>3月</code> が横に並んでいるため、月別に集計したいときには少し扱いにくい形です。</p>

<pre class="line-numbers"><code class="language-python">import pandas as pd

df = pd.DataFrame({
    &quot;社員ID&quot;: [&quot;E001&quot;, &quot;E002&quot;, &quot;E003&quot;],
    &quot;社員名&quot;: [&quot;佐藤&quot;, &quot;鈴木&quot;, &quot;田中&quot;],
    &quot;部署&quot;: [&quot;営業部&quot;, &quot;営業部&quot;, &quot;企画部&quot;],
    &quot;1月&quot;: [120000, 98000, 150000],
    &quot;2月&quot;: [135000, 110000, 142000],
    &quot;3月&quot;: [128000, 105000, 160000]
})

df</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">1月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">2月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">3月</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>このデータでは、<code>社員ID</code>、<code>社員名</code>、<code>部署</code> は社員を説明する列です。</p>
<p>一方で、<code>1月</code>、<code>2月</code>、<code>3月</code> は、月別の売上を表す列です。</p>
<p>今回目指す形は、次のとおりです。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">変換前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">変換後</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code>, <code>1月</code>, <code>2月</code>, <code>3月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code>, <code>月</code>, <code>売上</code></td>
</tr>
</tbody>
</table></div>
<p>つまり、社員を説明する列は残し、月別売上の列だけを縦にまとめます。</p>

<h2><span id="toc6">基本形：melt()で横持ちを縦持ちに変換する</span></h2>
<p><code>melt()</code> の基本形は次のとおりです。</p>
<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[残す列],
    value_vars=[縦にまとめる列],
    var_name="項目列の名前",
    value_name="値列の名前"
)
</code></pre>
<p>今回の場合は、社員情報を残し、月別売上の列を縦にまとめます。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">引数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">今回の指定</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">意味</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">そのまま残す列</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦にまとめる列</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>var_name</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元の列名を入れる列名</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_name</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>売上</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元の値を入れる列名</td>
</tr>
</tbody>
</table></div>

<h3><span id="toc7">melt()は3つに分けて考えると迷いにくい</span></h3>
<p><code>melt()</code> では、最初に次の3つを決めると迷いにくくなります。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">決めること</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">指定する引数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">今回の例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">そのまま残す列はどれか</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦にまとめる列はどれか</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">melt後の列名を何にするか</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>var_name</code>, <code>value_name</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code>, <code>売上</code></td>
</tr>
</tbody>
</table></div>
<p>初心者が一番迷いやすいのは、<code>id_vars</code> と <code>value_vars</code> の分け方です。</p>
<p>まずは「社員名や部署のように説明として残す列」と「1月・2月・3月のように縦へまとめる列」を分けて考えると、コードを書きやすくなります。</p>

<pre class="line-numbers"><code class="language-python">sales_long = df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)

sales_long</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p><code>1月</code>、<code>2月</code>、<code>3月</code> の列が、<code>月</code> 列にまとまりました。</p>
<p>それぞれの金額は、<code>売上</code> 列に入っています。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">元の列</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">melt後</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">そのまま残る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code> 列に入る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">各月の売上金額</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>売上</code> 列に入る</td>
</tr>
</tbody>
</table></div>
<p><code>melt()</code> では、まず「残す列」と「縦にまとめる列」を分けるのがポイントです。</p>

<h2><span id="toc8">melt()後に行数が増える理由</span></h2>
<p><code>melt()</code> を初めて使うと、行数が増えることに驚くかもしれません。</p>
<p>今回のデータは、変換前は3人分なので3行です。</p>
<p>しかし、1人につき <code>1月</code>、<code>2月</code>、<code>3月</code> の3つの売上があるため、<code>melt()</code> 後は次のように行数が増えます。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">変換前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">変換後</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3人 × 1行 = 3行</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3人 × 3か月 = 9行</td>
</tr>
</tbody>
</table></div>
<p><code>melt()</code> は、データを消しているのではありません。</p>
<p>横に並んでいた値を、縦に並べ直しているため、行数が増えるのは自然な動きです。</p>

<pre class="line-numbers"><code class="language-python">print(&quot;変換前の行数:&quot;, len(df))
print(&quot;変換後の行数:&quot;, len(sales_long))</code></pre>
<pre class="colab-output">変換前の行数: 3
変換後の行数: 9
</pre>
<p>このように、<code>melt()</code> 後は「元の行数 × 縦にまとめた列数」に近い行数になります。</p>
<p>今回であれば、3人 × 3か月なので9行です。</p>

<h2><span id="toc9">補足：元のindexを残したいときはignore_index=False</span></h2>
<p><code>melt()</code> は、通常は変換後に新しい連番indexを付けます。</p>
<p>多くの場合はそのままで問題ありません。</p>
<p>ただし、元の行番号やindexを確認しながら変換結果を見たいときは、<code>ignore_index=False</code> を指定できます。</p>
<p>初心者のうちは必須ではありませんが、<code>melt()</code> 後に「元のindexはどうなるのか」で迷ったときに知っておくと便利です。</p>

<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;,
    ignore_index=False
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p><code>ignore_index=False</code> を指定すると、変換前のindexが残ります。</p>
<p>今回の例では、元データの0行目、1行目、2行目が、それぞれ月の数だけ繰り返されます。</p>
<p>ただし、通常の分析では新しい連番indexで問題ないことが多いため、最初は省略して構いません。</p>

<h2><span id="toc10">id_varsの意味：そのまま残す列</span></h2>
<p><code>id_vars</code> には、melt後もそのまま残したい列を指定します。</p>
<p>今回の例では、次の列です。</p>
<ul>
<li><code>社員ID</code></li>
<li><code>社員名</code></li>
<li><code>部署</code></li>
</ul>
<p>初心者向けに言うと、<code>id_vars</code> は<strong>縦にまとめない列</strong>です。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">列</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">指定先</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">理由</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">社員を識別するため</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員名</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">誰の売上かを残すため</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>部署</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">部署別集計に使えるため</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦にまとめたい月別売上だから</td>
</tr>
</tbody>
</table></div>
<p><code>id_vars</code> に入れない列は、結果に残らないことがあります。</p>
<p>後で使いたい列は、<code>id_vars</code> に入れておきましょう。</p>

<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[&quot;社員名&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>この例では、<code>社員名</code> だけを <code>id_vars</code> にしたため、<code>社員ID</code> と <code>部署</code> は結果に残りません。</p>
<p>あとで部署別に集計したいなら、<code>部署</code> も <code>id_vars</code> に含める必要があります。</p>

<h2><span id="toc11">value_varsの意味：縦にまとめる列</span></h2>
<p><code>value_vars</code> には、縦にまとめたい列を指定します。</p>
<p>月別売上データなら、<code>1月</code>、<code>2月</code>、<code>3月</code> が該当します。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">引数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">役割</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">今回の例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">そのまま残す列</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>社員ID</code>, <code>社員名</code>, <code>部署</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_vars</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦にまとめる列</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code></td>
</tr>
</tbody>
</table></div>
<p><code>value_vars</code> は、「この列たちを1つの項目列と値列にまとめたい」と指定する場所です。</p>

<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    value_vars=[&quot;1月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>この例では、<code>value_vars</code> に <code>1月</code> と <code>3月</code> だけを指定しています。</p>
<p>そのため、<code>2月</code> は結果に含まれません。</p>
<p>分析対象にしたい列だけを選んで縦にまとめられるのが、<code>value_vars</code> の便利な点です。</p>

<h2><span id="toc12">var_nameとvalue_nameで列名をわかりやすくする</span></h2>
<p><code>var_name</code> と <code>value_name</code> を指定しない場合、melt後の列名は <code>variable</code> と <code>value</code> になります。</p>

<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;]
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">variable</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">value</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>このままでも処理はできますが、<code>variable</code> と <code>value</code> だけでは、何を表している列なのかがわかりにくいです。</p>
<p>そこで、次のように指定します。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">引数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">意味</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">今回の指定</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>var_name</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元の列名を入れる列の名前</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_name</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元の値を入れる列の名前</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>売上</code></td>
</tr>
</tbody>
</table></div>
<p>実務でも記事でも、<code>var_name</code> と <code>value_name</code> は指定しておくと読みやすくなります。</p>

<pre class="line-numbers"><code class="language-python">sales_long = df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)

sales_long</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p><code>variable</code> と <code>value</code> ではなく、<code>月</code> と <code>売上</code> という列名になりました。</p>
<p>あとで <code>groupby("月")</code> や <code>sales_long["売上"]</code> のように書くときも、意味が読み取りやすくなります。</p>

<h3><span id="toc13">value_nameは既存の列名と重ならない名前にする</span></h3>
<p><code>value_name</code> には、melt後の値列の名前を指定します。</p>
<p>この名前は、元のDataFrameにすでにある列名と重ならないようにするのが安全です。</p>
<p>たとえば、元データにすでに <code>売上</code> という列があるのに、<code>value_name="売上"</code> と指定すると、列名の重複やエラーの原因になることがあります。</p>
<p>今回のサンプルでは、元データに <code>売上</code> 列はなく、<code>1月</code>、<code>2月</code>、<code>3月</code> の値をまとめた列として新しく <code>売上</code> という名前を付けています。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">状況</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">おすすめ</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元データに <code>売上</code> 列がない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_name="売上"</code> でよい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元データにすでに <code>売上</code> 列がある</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_name="月別売上"</code> など別名にする</td>
</tr>
</tbody>
</table></div>
<p>細かい点ですが、実務データでは列名が増えやすいため、melt後の列名は元の列名と重ならないように確認しておきましょう。</p>

<h2><span id="toc14">value_varsを省略した場合の注意点</span></h2>
<p><code>value_vars</code> は省略できます。</p>
<p>ただし、省略すると、<code>id_vars</code> 以外の列がすべて縦にまとめられます。</p>

<pre class="line-numbers"><code class="language-python">df.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>今回のデータでは、<code>id_vars</code> 以外が <code>1月</code>、<code>2月</code>、<code>3月</code> だけなので問題ありません。</p>
<p>しかし、実際のCSVには <code>備考</code>、<code>登録日</code>、<code>メモ</code> のような列が含まれることがあります。</p>
<p>その場合、<code>value_vars</code> を省略すると、意図しない列まで縦にまとめられる可能性があります。</p>
<p>初心者のうちは、<code>value_vars</code> を明示するほうが安全です。</p>

<h3><span id="toc15">value_varsを省略すると不要な列まで入る例</span></h3>
<p>次のように、元データに <code>備考</code> 列があるケースを考えます。</p>
<p><code>備考</code> は売上ではないため、本来は <code>月</code> や <code>売上</code> にまとめたくない列です。</p>

<pre class="line-numbers"><code class="language-python">df_extra = df.copy()
df_extra[&quot;備考&quot;] = [&quot;重点顧客&quot;, &quot;通常&quot;, &quot;確認中&quot;]

df_extra</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">1月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">2月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">3月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">備考</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">重点顧客</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認中</td>
</tr>
</tbody>
</table></div>
<p>この状態で <code>value_vars</code> を省略すると、<code>id_vars</code> 以外の列がすべて縦にまとめられます。</p>
<p>つまり、<code>1月</code>、<code>2月</code>、<code>3月</code> だけでなく、<code>備考</code> まで <code>月</code> 列に入ってしまいます。</p>

<pre class="line-numbers"><code class="language-python">df_extra.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">備考</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">重点顧客</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">備考</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">11</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">備考</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認中</td>
</tr>
</tbody>
</table></div>
<p><code>備考</code> は売上ではないので、この結果は分析しにくい形です。</p>
<p>このようなミスを防ぐには、縦にまとめたい列を <code>value_vars</code> で明示します。</p>

<pre class="line-numbers"><code class="language-python">df_extra.melt(
    id_vars=[&quot;社員ID&quot;, &quot;社員名&quot;, &quot;部署&quot;, &quot;備考&quot;],
    value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
    var_name=&quot;月&quot;,
    value_name=&quot;売上&quot;
)</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">備考</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">重点顧客</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">重点顧客</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">重点顧客</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<p>このように、<code>value_vars</code> を指定すると、売上に関係する月別列だけを縦にまとめられます。</p>
<p>実際のCSVでは、メモ列、登録日、区分、備考などが混ざっていることがあります。初心者のうちは、<code>value_vars</code> を省略せずに明示するほうが安全です。</p>

<h2><span id="toc16">科目別点数データでもmelt()を使う</span></h2>
<p>月別売上だけでなく、科目別点数のようなデータでも <code>melt()</code> は使えます。</p>
<p>ここでは、<code>国語</code>、<code>数学</code>、<code>英語</code> が横に並んだデータを、<code>科目</code> 列と <code>点数</code> 列に変換します。</p>

<pre class="line-numbers"><code class="language-python">score_df = pd.DataFrame({
    &quot;生徒ID&quot;: [&quot;S001&quot;, &quot;S002&quot;, &quot;S003&quot;],
    &quot;氏名&quot;: [&quot;山田&quot;, &quot;田中&quot;, &quot;伊藤&quot;],
    &quot;クラス&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;],
    &quot;国語&quot;: [82, 75, 90],
    &quot;数学&quot;: [70, 88, 95],
    &quot;英語&quot;: [78, 84, 92]
})

score_df</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">生徒ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">氏名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">クラス</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">国語</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">数学</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">英語</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">山田</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">82</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">70</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">78</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">75</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">88</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">84</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">伊藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">90</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">95</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">92</td>
</tr>
</tbody>
</table></div>
<pre class="line-numbers"><code class="language-python">score_long = score_df.melt(
    id_vars=[&quot;生徒ID&quot;, &quot;氏名&quot;, &quot;クラス&quot;],
    value_vars=[&quot;国語&quot;, &quot;数学&quot;, &quot;英語&quot;],
    var_name=&quot;科目&quot;,
    value_name=&quot;点数&quot;
)

score_long</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">生徒ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">氏名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">クラス</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">科目</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">点数</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">山田</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">国語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">82</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">国語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">75</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">伊藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">国語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">90</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">山田</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数学</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">70</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数学</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">88</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">伊藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数学</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">95</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">山田</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">英語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">78</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">英語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">84</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">S003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">伊藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">英語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">92</td>
</tr>
</tbody>
</table></div>
<p><code>国語</code>、<code>数学</code>、<code>英語</code> が <code>科目</code> 列にまとまり、点数は <code>点数</code> 列に入りました。</p>
<p>この形にしておくと、科目ごとの平均点を出しやすくなります。</p>

<pre class="line-numbers"><code class="language-python">score_long.groupby(&quot;科目&quot;, as_index=False)[&quot;点数&quot;].mean()</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">科目</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">点数</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">国語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">82.333333</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数学</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">84.333333</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">英語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">84.666667</td>
</tr>
</tbody>
</table></div>
<p>この例では、<code>melt()</code> で科目ごとに集計しやすい形へ変換し、その後に <code>groupby()</code> で平均点を計算しています。</p>

<h2><span id="toc17">melt()した後にgroupby()で集計する</span></h2>
<p><code>melt()</code> のメリットは、変換後に <code>groupby()</code> へつなげやすいことです。</p>
<p>先ほど作成した <code>sales_long</code> を使って、月ごとの売上合計を確認してみます。</p>

<pre class="line-numbers"><code class="language-python">monthly_sales = sales_long.groupby(&quot;月&quot;, as_index=False)[&quot;売上&quot;].sum()

monthly_sales</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">368000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">387000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">393000</td>
</tr>
</tbody>
</table></div>
<p>縦持ちにしておくと、<code>月</code> という列を基準に集計できます。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月ごとの売上合計</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>groupby("月")["売上"].sum()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">部署ごとの売上合計</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>groupby("部署")["売上"].sum()</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">社員ごとの平均売上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>groupby("社員名")["売上"].mean()</code></td>
</tr>
</tbody>
</table></div>
<p><code>melt()</code> は集計の前処理、<code>groupby()</code> は集計本体と考えると整理しやすいです。</p>

<h2><span id="toc18">melt()した後にvalue_counts()で件数を確認する</span></h2>
<p><code>melt()</code> 後のカテゴリ列は、<code>value_counts()</code> でも扱いやすくなります。</p>
<p>たとえば、科目別点数データで、科目ごとの行数を確認してみます。</p>

<pre class="line-numbers"><code class="language-python">score_long[&quot;科目&quot;].value_counts()</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">count</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">科目</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">国語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数学</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">英語</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
</tr>
</tbody>
</table></div>
<p>この例では、各生徒に3科目分のデータがあるため、各科目が同じ件数になります。</p>
<p>実務では、商品名、カテゴリ、月、地域などを縦持ちにしておくと、カテゴリごとの件数確認がしやすくなります。</p>

<h2><span id="toc19">melt()した後に棒グラフで可視化する</span></h2>
<p>縦持ちデータに変換すると、Matplotlibの棒グラフにもつなげやすくなります。</p>
<p>ここでは、月ごとの売上合計を棒グラフで表示します。</p>
<p>Google Colabでは、日本語の軸ラベルやタイトルが文字化けする場合があります。この記事では <code>melt()</code> 後にグラフ化へ進む流れを確認することを目的にしているため、基本コードでは英語ラベルを使います。日本語で表示したい場合の対処法は、この後の補足で紹介します。</p>

<pre class="line-numbers"><code class="language-python">import matplotlib.pyplot as plt

monthly_sales = sales_long.groupby(&quot;月&quot;, as_index=False)[&quot;売上&quot;].sum()

plt.figure(figsize=(6, 4))
plt.bar(monthly_sales[&quot;月&quot;], monthly_sales[&quot;売上&quot;])
plt.xlabel(&quot;Month&quot;)
plt.ylabel(&quot;Sales&quot;)
plt.title(&quot;Monthly Sales&quot;)
plt.show()</code></pre>
<pre class="colab-output">/usr/local/lib/python3.12/dist-packages/IPython/core/pylabtools.py:151: UserWarning: Glyph 26376 (\N{CJK UNIFIED IDEOGRAPH-6708}) missing from font(s) DejaVu Sans.
  fig.canvas.print_figure(bytes_io, **kw)
</pre>
<figure class="colab-figure">
  <img decoding="async" src="images/figure1.png" alt="melt()で縦持ちに変換したデータを月別売上で集計した棒グラフ" loading="lazy">
  <figcaption>melt()で縦持ちに変換したデータを月別売上で集計した棒グラフ</figcaption>
</figure>
<p>流れは次のとおりです。</p>
<ol>
<li>横持ちデータを用意する</li>
<li><code>melt()</code> で縦持ちデータに変換する</li>
<li><code>groupby()</code> で月別に集計する</li>
<li>Matplotlibで棒グラフにする</li>
</ol>
<p><code>melt()</code> はグラフを描くメソッドではありません。</p>
<p>ただし、グラフ化しやすいデータの形を作る前処理として役立ちます。</p>

<h3><span id="toc20">補足：Colabでグラフの日本語ラベルが文字化けするとき</span></h3>
<p>Google ColabでMatplotlibのグラフを描くと、日本語のタイトルや軸ラベルが文字化けすることがあります。</p>
<p>この記事では、まず <code>melt()</code> の流れを理解しやすくするため、基本のグラフでは英語ラベルを使いました。</p>
<p>日本語で表示したい場合は、次のように <code>japanize-matplotlib</code> を使う方法があります。</p>

<pre class="line-numbers"><code class="language-python"># Colabで日本語ラベルを使いたい場合
!pip -q install japanize-matplotlib

import matplotlib.pyplot as plt
import japanize_matplotlib

monthly_sales = sales_long.groupby(&quot;月&quot;, as_index=False)[&quot;売上&quot;].sum()

plt.figure(figsize=(6, 4))
plt.bar(monthly_sales[&quot;月&quot;], monthly_sales[&quot;売上&quot;])
plt.xlabel(&quot;月&quot;)
plt.ylabel(&quot;売上&quot;)
plt.title(&quot;月別売上&quot;)
plt.show()</code></pre>
<p>この補足は、グラフの表示環境に関する内容です。</p>
<p><code>melt()</code> の使い方そのものは、英語ラベルでも日本語ラベルでも変わりません。</p>

<h2><span id="toc21">melt()とpivot()・pivot_table()の違い</span></h2>
<p><code>melt()</code>、<code>pivot()</code>、<code>pivot_table()</code> は、どれもDataFrameの形を変える場面で出てきます。</p>
<p>違いは、変換する向きと集計の有無です。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">メソッド</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">主な役割</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">変換の向き</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">集計</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横に並んだ列を縦にまとめる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横持ち → 縦持ち</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">しない</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦長データを横に広げる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦持ち → 横持ち</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">しない</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot_table()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">集計しながら横に広げる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦持ち → 集計表</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">する</td>
</tr>
</tbody>
</table></div>
<p><code>melt()</code> と <code>pivot()</code> は、ざっくり言うと逆方向の処理です。</p>

<pre class="line-numbers"><code class="language-python"># melt()で作った縦持ちデータ
sales_long</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">部署</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">売上</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">営業部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">E003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">企画部</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3月</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
</tbody>
</table></div>
<pre class="line-numbers"><code class="language-python"># 縦持ちデータを、社員名×月の横持ちデータに戻す例
sales_pivot = sales_long.pivot(
    index=&quot;社員名&quot;,
    columns=&quot;月&quot;,
    values=&quot;売上&quot;
)

sales_pivot</code></pre>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">1月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">2月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">3月</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">社員名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">佐藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">135000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">128000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">田中</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">150000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">142000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">160000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">鈴木</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">98000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">110000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">105000</td>
</tr>
</tbody>
</table></div>
<p>この記事では <code>melt()</code> を中心に扱っています。</p>
<p><code>pivot()</code> や <code>pivot_table()</code> の詳しい使い方は、集計表を作る場面で学ぶと理解しやすいです。</p>

<h2><span id="toc22">melt()とconcat()・merge()の違い</span></h2>
<p><code>melt()</code> は、1つのDataFrameの形を変える処理です。</p>
<p><code>concat()</code> や <code>merge()</code> は、複数のDataFrameを結合する処理です。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">メソッド</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">目的</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1つのDataFrameの形を変える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月別列を、月列と売上列に変換する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>concat()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">複数のDataFrameを上下・左右に結合する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月CSV、2月CSV、3月CSVを縦に結合する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>merge()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">キー列を使って別表を結合する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上データに社員マスタを結合する</td>
</tr>
</tbody>
</table></div>
<p>「列を縦にまとめたい」のか、「別のDataFrameをくっつけたい」のかで使い分けましょう。</p>

<h2><span id="toc23">melt()と他のメソッドを迷ったときの使い分け</span></h2>
<p><code>melt()</code> は便利ですが、すべてのデータ整形に使うメソッドではありません。</p>
<p>目的別に整理すると、次のようになります。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">使うメソッド</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横に並んだ月・科目・商品列を縦にまとめたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1月</code>, <code>2月</code>, <code>3月</code> → <code>月</code>, <code>売上</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦持ちデータを横持ちの表に戻したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>月</code> 列を <code>1月</code>, <code>2月</code>, <code>3月</code> の列に戻す</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">集計しながら横持ちの表を作りたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot_table()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">部署×月の売上合計表を作る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">複数のDataFrameを上下に結合したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>concat()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1月CSV、2月CSV、3月CSVを縦に結合する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">別表の情報をキーで結合したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>merge()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上データに社員マスタを結合する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">列名だけを変更したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>rename()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>氏名</code> を <code>社員名</code> に変更する</td>
</tr>
</tbody>
</table></div>
<p>検索していると、<code>melt()</code>、<code>pivot()</code>、<code>concat()</code>、<code>merge()</code> がまとめて出てくることがあります。</p>
<p>しかし、<code>melt()</code> の役割はあくまで、<strong>1つのDataFrameの中で、横に並んだ列を縦にまとめること</strong>です。</p>
<p>「列を縦にまとめたいのか」「表を結合したいのか」「列名を変えたいだけなのか」を先に分けると、使うメソッドを選びやすくなります。</p>

<h2><span id="toc24">よくあるミスと注意点</span></h2>
<p><code>melt()</code> で初心者がつまずきやすい点を整理します。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">よくあるミス</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">対策</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code> が集計する処理だと思う</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code> は形を変えるだけ。集計は <code>groupby()</code> などで行う</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code> と <code>value_vars</code> を逆にする</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>id_vars</code> は残す列、<code>value_vars</code> は縦にまとめる列</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>variable</code> と <code>value</code> の意味がわからない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>var_name</code> と <code>value_name</code> を指定する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_vars</code> を省略して意図しない列まで変換する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">初心者のうちは <code>value_vars</code> を明示する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>value_name</code> を既存の列名と重ねてしまう</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">元データにない列名を付ける</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code> 後にindexが変わって驚く</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">通常は新しいindexで問題ない。必要なら <code>ignore_index=False</code> を使う</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">列名変更やDataFrame結合にもmelt()を使おうとする</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">列名変更は <code>rename()</code>、結合は <code>concat()</code> / <code>merge()</code> を使う</td>
</tr>
</tbody>
</table></div>
<p>特に大事なのは、横持ちデータが悪いわけではないという点です。</p>
<p>表として見るだけなら、横持ちのままで問題ありません。</p>
<p>一方で、集計・条件抽出・グラフ化をしやすくしたい場合は、<code>melt()</code> で縦持ちにすることを検討するとよいです。</p>

<h2><span id="toc25">前処理の流れの中でmelt()を使うタイミング</span></h2>
<p><code>melt()</code> は、集計や可視化の直前に使うことが多いです。</p>
<p>流れとしては、次のように考えると自然です。</p>
<ol>
<li><code>read_csv()</code> でCSVを読み込む</li>
<li><code>head()</code> や <code>info()</code> でデータを確認する</li>
<li>欠損値、重複、型、列名を整える</li>
<li>横持ちデータなら <code>melt()</code> で縦持ちに変換する</li>
<li><code>groupby()</code> や <code>value_counts()</code> で集計する</li>
<li>Matplotlibでグラフ化する</li>
</ol>
<p>月別売上、科目別点数、商品別数量のように、同じ種類の項目が横に並んでいるデータでは、<code>melt()</code> を検討するとよいです。</p>

<h3><span id="toc26">補足：CSVで読み込んだデータにもmelt()は使える</span></h3>
<p>実際の分析では、手入力のサンプルデータではなく、CSVファイルを読み込んだDataFrameに対して <code>melt()</code> を使うこともあります。</p>
<p>考え方は同じです。</p>
<ul>
<li>残す列を <code>id_vars</code> に指定する</li>
<li>縦にまとめる列を <code>value_vars</code> に指定する</li>
<li>元の列名を入れる列名を <code>var_name</code> で決める</li>
<li>値を入れる列名を <code>value_name</code> で決める</li>
</ul>
<p>CSVを読み込んだ直後は、まず <code>head()</code> や <code>info()</code> で列名を確認してから、<code>melt()</code> を使うと安全です。</p>

<pre class="line-numbers"><code class="language-python"># 例：CSVを読み込んだあとにmelt()する場合
# df_csv = pd.read_csv(&quot;sales.csv&quot;)

# 実際には、CSVの列名に合わせて id_vars と value_vars を指定します。
# long_df = df_csv.melt(
#     id_vars=&quot;商品名&quot;,
#     value_vars=[&quot;1月&quot;, &quot;2月&quot;, &quot;3月&quot;],
#     var_name=&quot;月&quot;,
#     value_name=&quot;販売数&quot;
# )</code></pre>
<h2><span id="toc27">軽く知っておきたい関連メソッド</span></h2>
<p><code>melt()</code> に似た変形処理として、<code>stack()</code>、<code>unstack()</code>、<code>wide_to_long()</code> があります。</p>
<p>ただし、初心者のうちは、まず <code>melt()</code> の基本を理解すれば十分です。</p>
<div class="colab-table-wrap"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">メソッド</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">ざっくりした役割</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd; font-weight: 600; background: #f6f8fa;">この記事での扱い</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>melt()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">横持ちを縦持ちに変換する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">中心</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>stack()</code> / <code>unstack()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">インデックスを使って形を変える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">軽く触れるだけ</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>wide_to_long()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">規則的な列名をもとに縦長へ変換する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">発展</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">縦持ちを横持ちへ戻す</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">比較対象</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pivot_table()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">集計しながら横持ちへ変換する</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">比較対象</td>
</tr>
</tbody>
</table></div>
<p>最初からすべて覚える必要はありません。まずは、<code>melt()</code> を「横に増えた列を縦にまとめる基本メソッド」として理解しましょう。</p>

<h2><span id="toc28">まとめ</span></h2>
<p>この記事では、Pandasの <code>melt()</code> を使って、横持ちデータを縦持ちデータへ変換する方法を解説しました。</p>
<p>ポイントは次のとおりです。</p>
<ul>
<li><code>melt()</code> は、横に広がった列を縦長にまとめるメソッド</li>
<li><code>id_vars</code> は、そのまま残す列</li>
<li><code>value_vars</code> は、縦にまとめる列</li>
<li><code>var_name</code> は、元の列名を入れる列の名前</li>
<li><code>value_name</code> は、元の値を入れる列の名前</li>
<li><code>value_vars</code> を省略すると、意図しない列まで縦にまとめることがある</li>
<li><code>melt()</code> 後は、横に並んでいた値を縦に並べ直すため、行数が増えることがある</li>
<li><code>melt()</code> は集計ではなく、集計・可視化しやすい形へ整える前処理</li>
<li><code>melt()</code> と <code>pivot()</code> は、変換の向きが逆</li>
<li><code>melt()</code> 後は、<code>groupby()</code>、<code>value_counts()</code>、Matplotlibにつなげやすい</li>
</ul>
<p>月別売上、科目別点数、商品別数量のように、同じ種類の項目が横に並んでいる表では、<code>melt()</code> が役立ちます。</p>
<p>横持ちの表を見て「集計しにくい」「グラフにしにくい」と感じたら、まず <code>melt()</code> で縦持ちにできないかを考えてみましょう。</p>

<h2><span id="toc29">次に読みたい関連記事</span></h2>
<ul>
<li><p><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a><br/>
DataFrameの行・列の基本構造を確認したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門｜pandas で read_csv と to_csv を徹底解説</a><br/>
CSVを読み込んでから前処理する流れを確認したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-pivot/">Pandas pivotとpivot_tableの違い｜重複データ対応と集計方法</a><br/>
<code>melt()</code> と逆方向の変形である <code>pivot()</code> / <code>pivot_table()</code> を学びたい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a><br/>
<code>melt()</code> 後に集計へ進みたい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a><br/>
縦持ちにしたカテゴリ列の件数を数えたい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門：横棒・グループ化・積み上げまで解説</a><br/>
集計したデータを棒グラフで可視化したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-concat/">Pandas concat完全ガイド｜複数CSVからDataFrameを縦横結合する方法</a><br/>
複数のDataFrameを結合する処理と <code>melt()</code> の違いを整理したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-merge/">pandas mergeの使い方｜DataFrame結合（inner, left, outer）の違いと実例</a><br/>
キー列を使って別表を結合する方法を学びたい方におすすめです。</p>
</li>
</ul>


<!-- ▼▼▼ カテゴリから探す　 共通スタイル（カテゴリ）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc30"> カテゴリから探す</span></h3> <ul> 
<ul>
  <li><a href="https://pythondatalab.com/category/pandas/basic/">◀ Pandas 基礎</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ Pandas 抽出・前処理</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/aggregation/">◀ Pandas 集計・変形</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ Matplotlib　可視化</a></li> </ul> </div>
<!-- ▼▼▼ カテゴリから探す　共通スタイル（カテゴリ）終了▼▼▼ -->

<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>
<script>Prism.highlightAll();</script>
</div>



<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1777903786950" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">pandas melt()は何をするメソッドですか？</span></h3>
<div class="rank-math-answer ">

<p><code>melt()</code> は、横に広がった列を縦長にまとめるメソッドです。<br />たとえば、<code>1月</code>、<code>2月</code>、<code>3月</code> のような列を、<code>月</code> 列と <code>売上</code> 列に変換できます。</p>

</div>
</div>
<div id="faq-question-1777903811117" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">melt()はどんなときに使いますか？</span></h3>
<div class="rank-math-answer ">

<p>月別売上、科目別点数、商品別数量のように、同じ種類の情報が複数の列に分かれているときに使います。<br />集計、条件抽出、グラフ化をしやすい形に整えたい場合に向いています。</p>

</div>
</div>
<div id="faq-question-1777903821795" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">id_varsとvalue_varsの違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>id_vars</code> は、そのまま残す列です。<br /><code>value_vars</code> は、縦にまとめる列です。<br />月別売上データなら、社員名や部署は <code>id_vars</code>、<code>1月</code>、<code>2月</code>、<code>3月</code> は <code>value_vars</code> に指定します。</p>

</div>
</div>
<div id="faq-question-1777903832571" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">value_varsを省略してもよいですか？</span></h3>
<div class="rank-math-answer ">

<p>省略はできます。<br />ただし、<code>id_vars</code> 以外の列がすべて縦にまとめられるため、<code>備考</code> や <code>メモ</code> など不要な列まで入ることがあります。<br />初心者のうちは、<code>value_vars</code> を明示するほうが安全です。</p>

</div>
</div>
<div id="faq-question-1777903843836" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">variable列とvalue列は何を意味しますか？</span></h3>
<div class="rank-math-answer ">

<p><code>variable</code> 列には、元の列名が入ります。<br /><code>value</code> 列には、元のセルの値が入ります。<br /><code>var_name</code> と <code>value_name</code> を指定すると、<code>月</code>、<code>売上</code> のようにわかりやすい列名にできます。</p>

</div>
</div>
<div id="faq-question-1777903857932" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc36">melt()後に行数が増えるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>横に並んでいた値を縦に並べ直すためです。<br />たとえば、3人分のデータに3か月分の列がある場合、<code>melt()</code> 後は3人×3か月で9行になります。</p>

</div>
</div>
<div id="faq-question-1777903869428" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc37">melt()とpivot()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>melt()</code> は、横持ちデータを縦持ちデータに変換します。<br /><code>pivot()</code> は、縦持ちデータを横持ちデータに変換します。<br />ざっくり言うと、逆方向の処理です。</p>

</div>
</div>
<div id="faq-question-1777903883516" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc38">melt()したあとにgroupby()やグラフ化はできますか？</span></h3>
<div class="rank-math-answer ">

<p>できます。<br /><code>melt()</code> で縦持ちにしたあと、<code>groupby()</code> で集計し、Matplotlibでグラフ化する流れはよく使います。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-melt/">pandas melt()の使い方｜横持ちデータを縦持ちに変換する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-melt/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Pandas pivot と pivot_table を徹底解説！データ分析での使い分けと応用</title>
		<link>https://pythondatalab.com/pandas-pivot/</link>
					<comments>https://pythondatalab.com/pandas-pivot/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 09 Aug 2025 06:37:15 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=1074</guid>

					<description><![CDATA[<p>Pandas pivotとpivot_tableの違いを詳しく解説。重複データによるValueError回避方法、aggfuncの活用、クロス集計表作成などデータ分析の実践的テクニックを紹介します。 Converted  [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-pivot/">Pandas pivot と pivot_table を徹底解説！データ分析での使い分けと応用</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
Pandas pivotとpivot_tableの違いを詳しく解説。重複データによるValueError回避方法、aggfuncの活用、クロス集計表作成などデータ分析の実践的テクニックを紹介します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.css" />
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>

<!-- 余白を完全になくすCSS追加 -->
<style>
  pre[class*="language-"] {
    margin: 0 !important;
    padding: 1em;
  }
</style>

<script>Prism.highlightAll();</script>
<title>Converted Colab Notebook</title>
</head>
<body>

<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->
<p>本記事で pandas pivot の基本と注意点を最初に整理します。データ分析をするとき、データを表に整理することが大切です。特に、元のデータを見たい形に並べ替える「ピボット」という操作はよく使われます。これは、バラバラに記録されたデータ（<strong>ロング形式</strong>）を、分析しやすい形（<strong>ワイド形式</strong>）に変換する<strong>データ集計</strong>や<strong>データ分析</strong>の重要なステップです。</p>
<p>たとえば、日付ごとにバラバラに記録された売上データを、「月」を横軸（列）に、「商品」を縦軸（行）にして、それぞれの「売上合計」がすぐわかるような表にする、といった場合に使います。このように、元のバラバラした形（<strong>ロング形式</strong>と呼びます）から、分析しやすい形（<strong>ワイド形式</strong>と呼びます）に変換するのがピボットです。</p>
<p>Pandas という便利なツールには、このピボットを行うための <code>pivot()</code> と <code>pivot_table()</code> という機能があります。どちらも似ていますが、使うデータに同じ組み合わせ（例：同じ月、同じ商品）が複数あるかどうかや、合計などの計算をするかどうかで使い分ける必要があります。特に、重複するデータを<strong>集計</strong>しながら<strong>クロス集計表</strong>を作成する際には <code>pivot_table()</code> が強力です。</p>
<p>この記事では、Pandas の <code>pivot</code> と <code>pivot_table</code> の基本的な使い方から、同じ組み合わせのデータをまとめる方法、複数の項目で整理する方法、そしてどちらの機能を選べば良いかまで、実際のコードを見ながら詳しく説明します。<strong>「pandas pivot」</strong> や <strong>「pandas pivot_table」</strong> の使い方を知りたい方、データを分かりやすく整理したい方、<strong>データ分析</strong>や<strong>データ集計</strong>を効率化したい方はぜひ読んでみてください。</p>
<p>▶️ Pandas pivotやpivot_tableの公式ドキュメントも参考にしてください：
<style>
ul.custom-links {
  margin: 0;
  padding-left: 1.2em;
}
ul.custom-links li {
  margin-bottom: 2px; /* 行間を詰める */
  list-style-type: disc;
}
</style>

<ul class="custom-links">
  <li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" target="_blank">pandas DataFrame.pivot</a></li>
  <li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html" target="_blank">pandas.pivot_table</a></li>
</ul>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-5" checked><label class="toc-title" for="toc-checkbox-5">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">Pandas pivot() の基本と使い方：重複しないデータの変換</a></li><li><a href="#toc2" tabindex="0">Pandas pivot_table()：重複データの集計と柔軟なピボット</a><ol><li><a href="#toc3" tabindex="0">Pandas pivot() の重要な制約：重複データによるエラー</a></li><li><a href="#toc4" tabindex="0">Pandas pivot と pivot_table の使い分け まとめ</a></li></ol></li><li><a href="#toc5" tabindex="0">Pandas pivot_table() の応用テクニック：複数条件での集計と詳細設定</a><ol><li><a href="#toc6" tabindex="0">複数レベルのインデックス (MultiIndex) の作成</a></li><li><a href="#toc7" tabindex="0">複数レベルのカラム (MultiColumn) の作成</a></li><li><a href="#toc8" tabindex="0">実社会での具体的な応用例</a></li></ol></li><li><a href="#toc9" tabindex="0">&lt;code&gt;Pandas pivot_table()&lt;/code&gt; の便利な引数とトラブルシューティング</a><ol><li><a href="#toc10" tabindex="0">NaN 値の扱い方 (fill_value 引数)</a></li><li><a href="#toc11" tabindex="0">様々な aggfunc の指定方法</a></li><li><a href="#toc12" tabindex="0">大規模データにおけるパフォーマンス考慮点</a></li></ol></li><li><a href="#toc13" tabindex="0">まとめ：Pandas pivot_table をマスターしてデータ分析を加速しよう</a><ol><li><a href="#toc14" tabindex="0">関連記事</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">Pandas pivot() の基本と使い方：重複しないデータの変換</span></h2>
<p>Pandas の <code>pivot()</code> 関数は、データフレームをシンプルに再形成するために使用されます。この関数は、<code>index</code>, <code>columns</code>, <code>values</code> の 3 つの引数を取り、指定した列をインデックス、カラム、値として新しいデータフレームを作成します。<strong>データ分析</strong>の初期段階で、重複のないシンプルなデータを整形するのに役立ちます。</p>

<p><strong>重要な点として、<code>pivot()</code> は <code>index</code> と <code>columns</code> で指定したキーの組み合わせが一意である（重複がない）データに対してのみ使用できます。</strong></p>

<p>まずは、<code>pivot()</code> を使うための重複のないサンプル売上データを作成しましょう。このデータは、各月・各商品の売上が1行に記録されており、重複する組み合わせはありません。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
import pandas as pd
# 重複のないデータを作成
unique_sales_data = {&#x27;月&#x27;: [&#x27;2023-01&#x27;, &#x27;2023-01&#x27;, &#x27;2023-02&#x27;, &#x27;2023-02&#x27;, &#x27;2023-03&#x27;, &#x27;2023-03&#x27;],
                     &#x27;商品&#x27;: [&#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;りんご&#x27;, &#x27;バナナ&#x27;],
                     &#x27;売上（円）&#x27;: [1000, 800, 1100, 850, 1300, 950]}
unique_sales_df = pd.DataFrame(unique_sales_data)
display(unique_sales_df)
  </code>
</pre>


<div class="colab-df-container" id="df-fa52b84d-591f-4168-9ec0-c6ca7612316a">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">売上（円）</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1000</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">950</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-fa52b84d-591f-4168-9ec0-c6ca7612316a')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-fa52b84d-591f-4168-9ec0-c6ca7612316a button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-fa52b84d-591f-4168-9ec0-c6ca7612316a');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-2635e446-5c0f-4260-a7d9-2d99629b946c">
<button class="colab-df-quickchart" onclick="quickchart('df-2635e446-5c0f-4260-a7d9-2d99629b946c')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-2635e446-5c0f-4260-a7d9-2d99629b946c button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_11d79373-0129-4b48-8e90-fb9aae9c55b3">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('unique_sales_df')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_11d79373-0129-4b48-8e90-fb9aae9c55b3 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('unique_sales_df');
      }
      })();
    </script>
</div>
</div>
</div>

<p>この重複のない <code>unique_sales_df</code> を使って、<code>pivot()</code> の基本的な使い方を見てみましょう。ここでは、「月」を新しいデータフレームのインデックス、「商品」をカラム、「売上（円）」を値としてピボットします。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
unique_sales_pivot = unique_sales_df.pivot(index=&#x27;月&#x27;, columns=&#x27;商品&#x27;, values=&#x27;売上（円）&#x27;)
display(unique_sales_pivot)
  </code>
</pre>


<div class="colab-df-container" id="df-eb1729e0-c8ac-4ef5-a9c1-1ba90de28f02">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">950</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-eb1729e0-c8ac-4ef5-a9c1-1ba90de28f02')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-eb1729e0-c8ac-4ef5-a9c1-1ba90de28f02 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-eb1729e0-c8ac-4ef5-a9c1-1ba90de28f02');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-31093769-fe42-4e8b-ac1a-31ecfc1fd711">
<button class="colab-df-quickchart" onclick="quickchart('df-31093769-fe42-4e8b-ac1a-31ecfc1fd711')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-31093769-fe42-4e8b-ac1a-31ecfc1fd711 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_ecf087a3-3be0-46be-852e-cc4436b798d3">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('unique_sales_pivot')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_ecf087a3-3be0-46be-852e-cc4436b798d3 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('unique_sales_pivot');
      }
      })();
    </script>
</div>
</div>
</div>

<h2><span id="toc2">Pandas pivot_table()：重複データの集計と柔軟なピボット</span></h2>
<p><code>pandas.pivot_table()</code> は、<code>pivot()</code> よりも高機能で、特に<strong>インデックスとカラムの組み合わせに重複があるデータ</strong>の<strong>集計</strong>に特化しています。<strong>データ集計</strong>（Aggregation）を行いながらデータをピボットできる点が <code>pivot()</code> との最大の違いです。これにより、複雑な<strong>クロス集計表</strong>を簡単に作成できます。</p>
<p>pivot_table() は pivot() の引数 (<code>index</code>, <code>columns</code>, <code>values</code>) に加えて、<code>aggfunc</code> という重要な引数を持っています。<code>aggfunc</code> には、重複する値に対して適用したい集計関数（例: &#8216;sum&#8217;, &#8216;mean&#8217;, &#8216;count&#8217;, <code>np.sum</code> など）を指定します。</p>
<p>先ほどの <code>unique_sales_df</code> は重複がありませんでしたが、実際のビジネスデータでは同じ月、同じ商品でも複数の店舗や取引でデータが重複することがよくあります。このような場合に <code>pivot_table()</code> が役立ちます。<strong>データ分析</strong>において、このような重複データの<strong>集計</strong>は不可欠です。</p>
<p>重複を含むサンプルデータ <code>sales_df</code> を使用して、<code>pivot_table()</code> の使い方を見ていきましょう。このデータでは、同じ「月」と「商品」の組み合わせで複数の「店舗」のデータが含まれており、<strong>データ集計</strong>が必要なケースです。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_data = {&#x27;月&#x27;: [&#x27;2023-01&#x27;, &#x27;2023-01&#x27;, &#x27;2023-01&#x27;, &#x27;2023-02&#x27;, &#x27;2023-02&#x27;, &#x27;2023-02&#x27;, &#x27;2023-03&#x27;, &#x27;2023-03&#x27;, &#x27;2023-03&#x27;],
              &#x27;店舗&#x27;: [&#x27;A&#x27;, &#x27;A&#x27;, &#x27;B&#x27;, &#x27;B&#x27;, &#x27;A&#x27;, &#x27;A&#x27;, &#x27;B&#x27;, &#x27;B&#x27;, &#x27;A&#x27;],
              &#x27;商品&#x27;: [&#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;りんご&#x27;, &#x27;バナナ&#x27;, &#x27;バナナ&#x27;],
              &#x27;売上（円）&#x27;: [1000, 800, 1200, 900, 1100, 850, 1300, 950, 850],
              &#x27;売上原価（円）&#x27;: [700, 500, 700, 600, 700, 400, 700, 550, 500]}
sales_df = pd.DataFrame(sales_data)
display(sales_df)
  </code>
</pre>


<div class="colab-df-container" id="df-ae363eb3-2be6-4811-801f-52e5343d9b2b">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">店舗</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">売上（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">売上原価（円）</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">600</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">400</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">950</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">550</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-ae363eb3-2be6-4811-801f-52e5343d9b2b')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-ae363eb3-2be6-4811-801f-52e5343d9b2b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ae363eb3-2be6-4811-801f-52e5343d9b2b');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-3a9b375b-c9d9-4dcb-bd78-d9eed5120948">
<button class="colab-df-quickchart" onclick="quickchart('df-3a9b375b-c9d9-4dcb-bd78-d9eed5120948')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-3a9b375b-c9d9-4dcb-bd78-d9eed5120948 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_df9e3767-5d60-4bc7-9b9d-4a6c71f2d0d9">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_df')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_df9e3767-5d60-4bc7-9b9d-4a6c71f2d0d9 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_df');
      }
      })();
    </script>
</div>
</div>
</div>


<h3><span id="toc3">Pandas pivot() の重要な制約：重複データによるエラー</span></h3>
<p><code>pandas.pivot()</code> は、<code>index</code> と <code>columns</code> で指定したキーの組み合わせが一意である場合にのみ機能します。もし、指定した <code>index</code> と <code>columns</code> の組み合わせに複数の行が該当する場合、<code>pivot()</code> はどの値を新しいデータフレームに配置すれば良いか判断できず、<code>ValueError: Index contains duplicate entries, cannot reshape</code> のようなエラーが発生します。</p>
<p>例えば、以下のデータのように、2023-01月のりんごの売上データが複数存在する場合、<code>unique_sales_df.pivot(index='月', columns='商品', values='売上（円）')</code> を実行するとエラーになります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">売上（円）</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1000</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</td>
    </tr>
  </tbody>
</table>
<p>↑この重複がエラーの原因</p>
<p>このように、集計せずに単純なデータ再形成を行いたい場合に <code>pivot()</code> は便利ですが、データの重複が少しでもある場合は、後述する <code>pivot_table()</code> を使う必要があります。</p>
<p><code>sales_df</code> を使って、「月」をインデックス、「商品」をカラム、「売上（円）」を値として <code>pivot_table()</code> を実行し、重複する「月」と「商品」の組み合わせの「売上（円）」を合計してみましょう。<code>aggfunc='sum'</code> を指定します。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_table_sum = sales_df.pivot_table(index=&#x27;月&#x27;, columns=&#x27;商品&#x27;, values=&#x27;売上（円）&#x27;, aggfunc=&#x27;sum&#x27;)
display(sales_pivot_table_sum)
  </code>
</pre>


<div class="colab-df-container" id="df-07df3e11-768e-445d-bba7-b9aab057767b">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1750</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1800</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-07df3e11-768e-445d-bba7-b9aab057767b')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-07df3e11-768e-445d-bba7-b9aab057767b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-07df3e11-768e-445d-bba7-b9aab057767b');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-bdfc3d6c-6844-4d9a-82d2-c6cc0233ca96">
<button class="colab-df-quickchart" onclick="quickchart('df-bdfc3d6c-6844-4d9a-82d2-c6cc0233ca96')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-bdfc3d6c-6844-4d9a-82d2-c6cc0233ca96 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_06e8ac27-67b7-43f6-97b5-37aa6436125c">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_table_sum')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_06e8ac27-67b7-43f6-97b5-37aa6436125c button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_table_sum');
      }
      })();
    </script>
</div>
</div>
</div>

<p>ご覧のように、<code>pivot_table()</code> は重複する「月」と「商品」の組み合わせ（例: 2023-03 月のバナナ）に対して、指定した<strong>集計関数</strong> (<code>sum</code>) を適用して結果を返します。2023-03 月のバナナの売上は、店舗 B (950 円) と店舗 A (850 円) の合計値 (950 + 850 = 1800 円) となっています。このように、<code>pivot_table()</code> を使うことで、重複するデータを適切に<strong>集計</strong>し、<strong>クロス集計表</strong>を作成できます。</p>
<p>同様に、平均を計算したい場合は <code>aggfunc='mean'</code> を指定します。ここでは「売上原価（円）」の平均を見てみましょう。これも<strong>データ集計</strong>の一種です。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_table_mean = sales_df.pivot_table(index=&#x27;月&#x27;, columns=&#x27;商品&#x27;, values=&#x27;売上原価（円）&#x27;, aggfunc=&#x27;mean&#x27;)
display(sales_pivot_table_mean)
  </code>
</pre>


<div class="colab-df-container" id="df-cfe67ed8-aec6-4eb3-8594-45374a923251">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">525.0</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-cfe67ed8-aec6-4eb3-8594-45374a923251')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-cfe67ed8-aec6-4eb3-8594-45374a923251 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-cfe67ed8-aec6-4eb3-8594-45374a923251');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-1cfb4b52-f391-4087-a80f-a95959dbf5d4">
<button class="colab-df-quickchart" onclick="quickchart('df-1cfb4b52-f391-4087-a80f-a95959dbf5d4')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-1cfb4b52-f391-4087-a80f-a95959dbf5d4 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_610bc51e-930d-4ae2-a02d-57704dc7eadb">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_table_mean')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_610bc51e-930d-4ae2-a02d-57704dc7eadb button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_table_mean');
      }
      })();
    </script>
</div>
</div>
</div>

<h3><span id="toc4">Pandas pivot と pivot_table の使い分け まとめ</span></h3>
<p>Pandas でデータフレームのピボットを行う際に、<code>pivot()</code> と <code>pivot_table()</code> のどちらを使うべきか迷うことがあります。以下にそれぞれの特徴と使い分けのポイントをまとめます。<strong>データ分析</strong>の目的に応じて適切な関数を選ぶことが重要です。</p>
<ul>
  <li><strong><code>pandas.pivot()</code></strong>: <code>index</code> と <code>columns</code> で指定するキーの組み合わせが<strong>一意である</strong>データにのみ使用できます。単純なデータの形を変える（再形成する）ことに特化しており、<strong>集計は行いません</strong>。重複がないことが確実な、シンプルなデータ変換に適しています。<strong>データ分析</strong>の初期段階での整形に利用されることがあります。</li>
  <li><strong><code>pandas.pivot_table()</code></strong>: <code>index</code> と <code>columns</code> で指定するキーの組み合わせに<strong>重複があっても使用できます</strong>。重複する値に対して <code>aggfunc</code> で指定した<strong>集計処理を行います</strong>。<strong>データ集計</strong>と同時にデータの形を変換したい場合や、データの重複が予想される場合に適しています。これにより、詳細な<strong>クロス集計表</strong>を作成できます。</li>
</ul>
<p><strong>結論として、データの重複の可能性がある場合は、迷わず <code>pivot_table()</code> を使用するのが安全で一般的です。</strong> <strong>データ分析</strong>において、生のデータには重複が含まれることが多いため、<code>pivot_table()</code> がより頻繁に利用されます。重複がないことが保証されている、非常にシンプルなケースでのみ <code>pivot()</code> を検討すると良いでしょう。</p>
<h2><span id="toc5">Pandas pivot_table() の応用テクニック：複数条件での集計と詳細設定</span></h2>
<p><code>pivot_table()</code> は、単一の列だけでなく、複数の列を組み合わせてインデックスやカラムとして使用することで、より複雑で多角的な<strong>データ集計</strong>・<strong>データ分析</strong>を行うことができます。これにより、データの階層的な構造を表現した<strong>クロス集計表</strong>を作成することが可能です。<strong>データ分析</strong>において、多次元的な視点からデータを把握するのに非常に役立ちます。</p>
<h3><span id="toc6">複数レベルのインデックス (MultiIndex) の作成</span></h3>
<p><code>index</code> 引数に列名のリストを指定することで、複数のレベルを持つ階層的なインデックス（MultiIndex）を作成できます。例えば、「月」と「店舗」をインデックス、「商品」をカラム、「売上原価（円）」を値として、それぞれの合計を<strong>集計</strong>してみましょう。これは<strong>データ集計</strong>の一例であり、店舗ごとの月別売上原価の傾向を把握するのに役立ちます。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_multi_index = sales_df.pivot_table(index=[&#x27;月&#x27;, &#x27;店舗&#x27;], columns=&#x27;商品&#x27;, values=&#x27;売上原価（円）&#x27;, aggfunc=&#x27;sum&#x27;)
display(sales_pivot_multi_index)
  </code>
</pre>


<div class="colab-df-container" id="df-03ad12e1-67a7-4e8b-8a5d-177b7721489c">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">店舗</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th rowspan="2" style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;" valign="top">2023-01</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
<tr>
<th rowspan="2" style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;" valign="top">2023-02</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">400.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">600.0</td>
</tr>
<tr>
<th rowspan="2" style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;" valign="top">2023-03</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">550.0</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-03ad12e1-67a7-4e8b-8a5d-177b7721489c')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-03ad12e1-67a7-4e8b-8a5d-177b7721489c button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-03ad12e1-67a7-4e8b-8a5d-177b7721489c');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-cdf8da28-0588-419d-b750-d0689f85f4c5">
<button class="colab-df-quickchart" onclick="quickchart('df-cdf8da28-0588-419d-b750-d0689f85f4c5')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-cdf8da28-0588-419d-b750-d0689f85f4c5 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_7b07c985-ca19-408d-a309-518ddb339923">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_multi_index')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_7b07c985-ca19-408d-a309-518ddb339923 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_multi_index');
      }
      })();
    </script>
</div>
</div>
</div>

<p>このように、外側のレベルに「月」、その内側のレベルに「店舗」という階層構造を持つインデックスが作成されました。</p>
<h3><span id="toc7">複数レベルのカラム (MultiColumn) の作成</span></h3>
<p>同様に、<code>columns</code> 引数に列名のリストを指定することで、複数のレベルを持つ階層的なカラム（MultiColumn）を作成できます。ここでは、「月」をインデックス、「店舗」と「商品」をカラム、「売上（円）」を値として、それぞれの合計を集計してみましょう。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_multi_columns = sales_df.pivot_table(index=&#x27;月&#x27;, columns=[&#x27;店舗&#x27;, &#x27;商品&#x27;], values=&#x27;売上（円）&#x27;, aggfunc=&#x27;sum&#x27;)
display(sales_pivot_multi_columns)
  </code>
</pre>


<div class="colab-df-container" id="df-cee6c02e-cb2d-4c35-89ed-3e0d4852bdaa">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }

    .dataframe thead tr:last-of-type th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">店舗</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">B</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">950.0</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-cee6c02e-cb2d-4c35-89ed-3e0d4852bdaa')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-cee6c02e-cb2d-4c35-89ed-3e0d4852bdaa button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-cee6c02e-cb2d-4c35-89ed-3e0d4852bdaa');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-e7c64537-b2ab-4736-b3de-defb7bd2615b">
<button class="colab-df-quickchart" onclick="quickchart('df-e7c64537-b2ab-4736-b3de-defb7bd2615b')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-e7c64537-b2ab-4736-b3de-defb7bd2615b button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_a9470b16-9132-48c8-9fdc-3976c67d2c9b">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_multi_columns')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_a9470b16-9132-48c8-9fdc-3976c67d2c9b button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_multi_columns');
      }
      })();
    </script>
</div>
</div>
</div>

<p>外側のレベルに「店舗」、その内側のレベルに「商品」という階層構造を持つカラムが作成されました。<code>pivot_table()</code> を活用することで、このように様々な切り口でデータを集計し、ビジネスの意思決定に役立つインサイトを得ることが可能になります。</p>
<p>&gt;『インサイト』とは、データ分析から得られる、物事の本質を見抜く洞察や、次に取るべき行動のヒントになるような深い理解のことです。</p>
<h3><span id="toc8">実社会での具体的な応用例</span></h3>
<p><code>pivot_table()</code> は様々な種類の<strong>データ分析</strong>に活用できます。いくつか具体的なシナリオを見てみましょう。これにより、いかに<code>pivot_table()</code>が<strong>データ集計</strong>と<strong>クロス集計表</strong>作成に役立つかが分かります。</p>
<p><strong>例 1：EC サイトの売上データ</strong></p>
<p>EC サイトの売上データがあるとします。ここには、注文 ID、顧客 ID、購入日、商品カテゴリ、商品名、価格などの情報が含まれています。<code>pivot_table()</code> を使うと、以下のような<strong>データ分析</strong>が可能です。</p>
<ul>
  <li><strong>月別の商品カテゴリ別売上集計:</strong></li>
</ul>
<p><code>sales_df.pivot_table(index='購入月', columns='商品カテゴリ', values='価格', aggfunc='sum')</code><br>
→ 各月のどの商品カテゴリがどれだけ売れているか一目で把握できます。これは典型的な<strong>クロス集計表</strong>を用いた<strong>データ集計</strong>です。</p>
<ul>
  <li><strong>顧客別の購入商品集計:</strong></li>
</ul>
<p><code>sales_df.pivot_table(index='顧客ID', columns='商品名', values='注文ID', aggfunc='count', fill_value=0)</code><br>
→ 各顧客がどの商品をいくつ購入したかを知ることができます。リピート購入されている商品を特定するのに役立ちます。顧客行動の<strong>データ分析</strong>に繋がります。</p>
<p><strong>例 2：顧客データ</strong></p>
<p>顧客データには、顧客 ID、年齢、性別、居住地域、最終購入日などの情報が含まれているとします。</p>
<ul>
  <li><strong>地域別の性別構成比:</strong></li>
</ul>
<p><code>customer_df.pivot_table(index='居住地域', columns='性別', values='顧客ID', aggfunc='count', fill_value=0)</code><br>
→ どの地域の顧客層がどの性別に偏っているかを確認できます。これも<strong>クロス集計表</strong>による<strong>データ分析</strong>の一例です。</p>
<p><strong>例 3：アンケートデータ</strong></p>
<p>製品やサービスに関するアンケートデータがあるとします。回答者の属性（年齢層、職業など）と、各質問への回答（5 段階評価など）が含まれています。</p>
<ul>
  <li><strong>年齢層別の質問評価平均:</strong></li>
</ul>
<p><code>survey_df.pivot_table(index='年齢層', columns='質問項目', values='評価点', aggfunc='mean')</code><br>
→ どの年齢層が特定の質問項目に対してどのような評価をしているかの平均を知ることができます。製品改善の優先順位付けに役立ちます。アンケート結果の<strong>データ集計</strong>と<strong>データ分析</strong>に有効です。</p>
<p>これらの例のように、<code>pivot_table()</code> はビジネスデータの様々な切り口での<strong>データ集計</strong>・<strong>データ分析</strong>に非常に強力なツールとなります。あなたの持っているデータをどのように<strong>集計</strong>・<strong>分析</strong>したいかを考え、適切な <code>index</code>, <code>columns</code>, <code>values</code>, <code>aggfunc</code> を指定することで、データから有用なインサイトを引き出すことができます。<strong>クロス集計表</strong>の作成は、<strong>データ分析</strong>の基本であり、<code>pivot_table()</code>はその中心的な役割を担います。</p>

<h2><span id="toc9">&lt;code&gt;Pandas pivot_table()&lt;/code&gt; の便利な引数とトラブルシューティング</span></h2>
<p><code>pivot_table()</code> をより効果的に使用するための便利な引数や、よく遭遇する問題とその解決策について解説します。これにより、<strong>データ集計</strong>や<strong>データ分析</strong>の効率をさらに向上させることができます。</p>
<h3><span id="toc10">NaN 値の扱い方 (fill_value 引数)</span></h3>
<p>ピボットした結果のデータフレームで、元のデータに存在しないインデックスとカラムの組み合わせには、デフォルトで <code>NaN</code> (Not a Number) が表示されます。これは、その組み合わせに対応するデータがなかったことを意味します。</p>
<p>分析や後続処理の都合上、これらの <code>NaN</code> を特定の値（例えば 0）で埋めたい場合は、<code>fill_value</code> 引数を使用します。</p>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_multi_columns = sales_df.pivot_table(index=&#x27;月&#x27;, columns=[&#x27;店舗&#x27;, &#x27;商品&#x27;], values=&#x27;売上（円）&#x27;, aggfunc=&#x27;sum&#x27;,fill_value=0)
display(sales_pivot_multi_columns)
  </code>
</pre>


<div class="colab-df-container" id="df-005d1e8e-0eb8-493f-ac6b-f80ec1e64c93">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }

    .dataframe thead tr:last-of-type th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">店舗</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">B</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">850</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">950</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-005d1e8e-0eb8-493f-ac6b-f80ec1e64c93')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-005d1e8e-0eb8-493f-ac6b-f80ec1e64c93 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-005d1e8e-0eb8-493f-ac6b-f80ec1e64c93');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-5c52dd3c-797b-4333-8b4f-f581411f7f01">
<button class="colab-df-quickchart" onclick="quickchart('df-5c52dd3c-797b-4333-8b4f-f581411f7f01')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-5c52dd3c-797b-4333-8b4f-f581411f7f01 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_3897968f-7869-4dc5-be49-49693ebc1663">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_multi_columns')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_3897968f-7869-4dc5-be49-49693ebc1663 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_multi_columns');
      }
      })();
    </script>
</div>
</div>
</div>

<p>fill_value=0 を指定することで、データが存在しなかった箇所が 0 で埋められていることが確認できます。これは、クロス集計表を見やすくしたり、後続の計算処理でエラーが出ないようにするための便利な機能です。データ分析においては、欠損値の適切な処理が重要になります。</p>
<h3><span id="toc11">様々な aggfunc の指定方法</span></h3>
<p><code>aggfunc</code> には、<strong>集計関数</strong>名を文字列で指定する以外にも、より柔軟な指定方法があります。これにより、<strong>データ集計</strong>のニーズに合わせて多様な計算を適用できます。</p>
<ul><li>  <strong>集計関数のリスト</strong>: 複数の<strong>集計</strong>（例: 合計と平均）を一度に行いたい場合に便利です。</li></ul>
<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_multi_agg = sales_df.pivot_table(index=&#x27;月&#x27;, columns=&#x27;商品&#x27;, values=&#x27;売上（円）&#x27;, aggfunc=[&#x27;sum&#x27;, &#x27;mean&#x27;])
display(sales_pivot_multi_agg)
  </code>
</pre>


<div class="colab-df-container" id="df-6c8799ac-7b5c-4b71-ad15-289fca012787">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }

    .dataframe thead tr:last-of-type th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">sum</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">mean</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1750</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">875.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900.0</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-6c8799ac-7b5c-4b71-ad15-289fca012787')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-6c8799ac-7b5c-4b71-ad15-289fca012787 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-6c8799ac-7b5c-4b71-ad15-289fca012787');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-7712db05-8ca9-4872-b1da-6ffb850aa15a">
<button class="colab-df-quickchart" onclick="quickchart('df-7712db05-8ca9-4872-b1da-6ffb850aa15a')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-7712db05-8ca9-4872-b1da-6ffb850aa15a button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_dd19f51d-d97c-4270-8b5d-316e65e446f0">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_multi_agg')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_dd19f51d-d97c-4270-8b5d-316e65e446f0 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_multi_agg');
      }
      })();
    </script>
</div>
</div>
</div>

<ul><li>  <strong>列ごとの集計関数を定義する辞書</strong>: 異なる列に対して異なる<strong>集計関数</strong>を適用したい場合に便利です。<code>values</code> 引数も辞書形式で指定する必要があります。これは、例えば売上は合計、利益率は平均、といった異なる種類の<strong>データ集計</strong>を同時に行いたい場合に有効です。</li></ul>

<pre class="language-python" data-prismjs-copy>
  <code class="language-python">
sales_pivot_dict_agg = sales_df.pivot_table(index=&#x27;月&#x27;, columns=&#x27;商品&#x27;, values={&#x27;売上（円）&#x27;: &#x27;sum&#x27;, &#x27;売上原価（円）&#x27;: &#x27;mean&#x27;})
display(sales_pivot_dict_agg)
  </code>
</pre>


<div class="colab-df-container" id="df-10af0bc1-9955-425e-a529-471ce7d5386b">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead tr th {
        text-align: left;
    }

    .dataframe thead tr:last-of-type th {
        text-align: right;
    }
</style>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">売上原価（円）</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">売上（円）</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">りんご</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">バナナ</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">月</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-01</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-02</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">500.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1100.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">875.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2023-03</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">700.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">525.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1300.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900.0</td>
</tr>
</tbody>
</table>
</div>
<div class="colab-df-buttons">
<div class="colab-df-container">
<button class="colab-df-convert" onclick="convertToInteractive('df-10af0bc1-9955-425e-a529-471ce7d5386b')" style="display:none;" title="Convert this dataframe to an interactive table.">
<svg height="24px" viewbox="0 -960 960 960" xmlns="http://www.w3.org/2000/svg">
<path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"></path>
</svg>
</button>
<style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>
<script>
      const buttonEl =
        document.querySelector('#df-10af0bc1-9955-425e-a529-471ce7d5386b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-10af0bc1-9955-425e-a529-471ce7d5386b');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
</div>
<div id="df-299dc0b7-d5f2-4593-9571-25d2f5ff741a">
<button class="colab-df-quickchart" onclick="quickchart('df-299dc0b7-d5f2-4593-9571-25d2f5ff741a')" style="display:none;" title="Suggest charts">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<g>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"></path>
</g>
</svg>
</button>
<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>
<script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-299dc0b7-d5f2-4593-9571-25d2f5ff741a button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
</div>
<div id="id_128d1f63-caa4-4e2d-b993-6cb15bdf0f5e">
<style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
<button class="colab-df-generate" onclick="generateWithVariable('sales_pivot_dict_agg')" style="display:none;" title="Generate code using this dataframe.">
<svg height="24px" viewbox="0 0 24 24" width="24px" xmlns="http://www.w3.org/2000/svg">
<path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"></path>
</svg>
</button>
<script>
      (() => {
      const buttonEl =
        document.querySelector('#id_128d1f63-caa4-4e2d-b993-6cb15bdf0f5e button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_pivot_dict_agg');
      }
      })();
    </script>
</div>
</div>
</div>

<h3><span id="toc12">大規模データにおけるパフォーマンス考慮点</span></h3>
<p>大規模なデータセットに対して <code>pivot_table()</code> を実行する場合、処理に時間がかかったり、メモリを大量に消費したりする可能性があります。<strong>データ分析</strong>において、パフォーマンスは重要な要素です。パフォーマンスを向上させるためには、以下の点を考慮してください。</p>
<ul><li>  <strong>不要な列を事前に削除</strong>: ピボットに関係のない列は、事前に DataFrame から削除することで、メモリ使用量と処理時間を削減できます。<strong>データ前処理</strong>の段階で<strong>データ分析</strong>に必要な列のみを選択することが重要です。</li><li>  <strong>データの型を最適化</strong>: 特に文字列データが多い列は、カテゴリ型 (<code>category</code>) に変換することでメモリ効率が向上する場合があります。適切なデータ型を使用することは、大規模データの<strong>データ集計</strong>において特に有効です。</li><li>  <strong>データ型の確認</strong>: 数値データがオブジェクト型 (<code>object</code>) になっていると計算が遅くなるため、適切な数値型 (<code>int</code>, <code>float</code>) に変換します。<strong>データ分析</strong>の精度と速度に影響します。</li><li>  <strong>チャンク処理</strong>: 非常に大きなデータセットの場合は、データを小さなチャンク（塊）に分割して <code>pivot_table()</code> を適用し、後で結果を結合することも有効な手段です。メモリが限られている環境での<strong>データ集計</strong>に役立ちます。</li></ul>

<h2><span id="toc13">まとめ：Pandas pivot_table をマスターしてデータ分析を加速しよう</span></h2>
<p>本記事では、Pandas ライブラリにおけるデータ再形成と<strong>データ集計</strong>のための主要な関数である <code>pivot()</code> と <code>pivot_table()</code> について詳しく解説しました。これらの関数は、<strong>データ分析</strong>において<strong>クロス集計表</strong>を作成する上で非常に重要です。</p>
<ul>
  <li><strong><code>pandas.pivot()</code></strong>: <code>index</code> と <code>columns</code> の組み合わせが一意であるデータに対して、シンプルなデータ再形成を行います。<strong>データ集計</strong>機能はありません。シンプルな<strong>データ分析</strong>の初期整形に利用します。</li>
  <li><strong><code>pandas.pivot_table()</code></strong>: <code>index</code> と <code>columns</code> の組み合わせに重複があるデータを含む、より柔軟な<strong>データ集計</strong>と再形成を行います。<code>aggfunc</code> 引数で様々な<strong>集計関数</strong>を指定できます。<strong>クロス集計表</strong>の作成や詳細な<strong>データ分析</strong>に不可欠です。</li>
</ul>
<p><code>pivot_table()</code> は、生のデータを<strong>データ分析</strong>に適した<strong>クロス集計表</strong>の形式に変換するための、<strong>データ分析</strong>において非常に重要なツールです。売上データの月別・商品別<strong>集計</strong>、アンケート結果の<strong>クロス集計</strong>、各種レポート作成など、幅広い場面でその強力な機能を発揮します。<strong>データ分析</strong>の効率と質を高めるために、<code>pivot_table()</code>は欠かせません。</p>
<p>この記事で解説した内容を参考に、ぜひあなたの<strong>データ分析</strong>ワークフローに <code>pivot_table()</code> を積極的に取り入れてみてください。実際に様々なデータに対して <code>pivot_table()</code> を試すことで、さらに理解を深めることができるでしょう。<strong>データ集計</strong>と<strong>クロス集計表</strong>の作成をマスターし、<strong>データ分析</strong>を加速させましょう。</p>

</body>
</html>





<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc14">関連記事</span></h3> <ul> 
<ul>
  <li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li> </ul> </div>
<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ -->



<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->



<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>



<p class="wp-block-paragraph"></p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-pivot/">Pandas pivot と pivot_table を徹底解説！データ分析での使い分けと応用</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-pivot/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas MultiIndex完全ガイド｜階層型インデックスの作成・選択・集計方法</title>
		<link>https://pythondatalab.com/pandas-multiindex/</link>
					<comments>https://pythondatalab.com/pandas-multiindex/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 02 Aug 2025 09:39:45 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=1035</guid>

					<description><![CDATA[<p>pandasのMultiIndex（階層型インデックス）を図解で理解。作成・選択・集計・stack/unstackなど実務で役立つ操作を丁寧に解説。 💡 Pandas DataFrame入門シリーズ このページは「Pan [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-multiindex/">pandas MultiIndex完全ガイド｜階層型インデックスの作成・選択・集計方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
pandasのMultiIndex（階層型インデックス）を図解で理解。作成・選択・集計・stack/unstackなど実務で役立つ操作を丁寧に解説。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.css" />
  <script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
  <style>
    pre[class*="language-"] {
      margin: 0 !important;
      padding: 1em;
    }
    table.wp-block-table td:first-child, table.wp-block-table th:first-child {
      min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;
    }
    table.wp-block-table td:not(:first-child), table.wp-block-table th:not(:first-child) {
      white-space: nowrap; padding: 0.2em 0.4em;
    }
  </style>
  <script>Prism.highlightAll();</script>
</head>
<body>

<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->


<p>データ分析でこんなことを思ったことはありませんか？</p>
<ul>
<li>複数の条件（例えば「ある月の特定の店舗での売上」）でデータを絞り込みたいけど、どうすれば効率的なんだろう？</li>
<li>店舗別、商品別、さらには「月ごとの店舗別」のように、様々な粒度でデータを集計して比較したいけど、もっと簡単な方法はないかな？</li>
</ul>
<p>この記事では、pandas の<strong>階層型インデックス (pandas MultiIndex)</strong> を使うことで、驚くほどスマートに解決できます！</p>
<p>pandas の MultiIndex（階層型インデックス）は、DataFrame の行や列に複数のレベルのラベルを付けることができる機能です。これにより、スプレッドシートでいうところの「複数行の見出し」のような構造をデータに持たせることができ、複雑なデータも直感的に、そして効率的に扱えるようになります。</p>
<p>pandas MultiIndex を使うと、次のような分析や操作が驚くほど簡単になります！</p>
<ul>
<li><strong>特定の条件での絞り込み</strong>: 「2023 年 1 月の A 店のりんごの売上だけを見たい」「特定の期間の B 店の全商品データを取り出したい」といった、複数の条件を組み合わせたデータ抽出が直感的に行えます。</li>
<li><strong>柔軟な集計</strong>: 「店舗ごとの合計売上」「月ごとの商品別売上」「商品ごとの全店舗での平均売上」など、様々な粒度での集計が効率的に行え、ビジネスの傾向分析に役立ちます。</li>
<li><strong>比較分析</strong>: 異なる店舗間や商品間でのパフォーマンス比較、時系列での変化の追跡などが容易になり、データに基づいた意思決定をサポートします。</li>
</ul>
<p>売上データを例に、pandas MultiIndex の基本的な考え方から、データの準備、選択、集計、そして操作方法までを、具体的なコードを通して学んでいきましょう！</p>

<p>▶️ MultiIndexの公式ドキュメントも参考にしてください：<br /><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.MultiIndex.html" target="_blank">pandas.MultiIndex Documentation</a></p>
 


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-7" checked><label class="toc-title" for="toc-checkbox-7">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">Pandas MultiIndex (階層型インデックス) の作成方法とサンプルデータ</a><ol><li><a href="#toc2" tabindex="0">サンプルデータの作成</a></li><li><a href="#toc3" tabindex="0">行方向への階層型インデックス（pandas MultiIndex）の設定 (set_index)</a></li></ol></li><li><a href="#toc4" tabindex="0">Pandas MultiIndex DataFrame からのデータ選択・絞り込み (loc, iloc)</a><ol><li><a href="#toc5" tabindex="0">特定の列（カラム）の選択</a><ol><li><a href="#toc6" tabindex="0">単一列の選択</a></li><li><a href="#toc7" tabindex="0">複数列の選択</a></li></ol></li><li><a href="#toc8" tabindex="0">特定の行の位置による選択 (.iloc)</a></li></ol></li><li><a href="#toc9" tabindex="0">階層型インデックス（pandas MultiIndex）を使ったラベルによるデータの選択・絞り込み (.loc)</a><ol><li><a href="#toc10" tabindex="0">複数レベルのインデックスラベルによる特定の組み合わせの選択</a></li><li><a href="#toc11" tabindex="0">複数レベルにまたがる要素の選択 (slice(None)の活用)</a></li><li><a href="#toc12" tabindex="0">単一レベルのインデックスラベルによる選択</a></li><li><a href="#toc13" tabindex="0">.loc使用時のパフォーマンスに関する注意点 (PerformanceWarningとsort_index)</a></li></ol></li><li><a href="#toc14" tabindex="0">Pandas MultiIndex を使った高度なデータ抽出・絞り込み</a><ol><li><a href="#toc15" tabindex="0">特定の月と店舗のデータを絞り込む</a></li></ol></li><li><a href="#toc16" tabindex="0">Pandas MultiIndex でのデータ集計 (groupby level)</a><ol><li><a href="#toc17" tabindex="0">単一インデックスレベルでの集計 (例: 店舗別)</a><ol><li><a href="#toc18" tabindex="0">【補足】groupbyのaxis引数に関する警告について</a></li></ol></li><li><a href="#toc19" tabindex="0">単一インデックスレベルでの集計 (例: 月別)</a></li><li><a href="#toc20" tabindex="0">複数インデックスレベルでの集計 (例: 月と店舗別)</a></li></ol></li><li><a href="#toc21" tabindex="0">MultiIndex のリセットと削除</a><ol><li><a href="#toc22" tabindex="0">階層型インデックス（pandas MultiIndex）のリセット (reset_index)</a></li></ol></li><li><a href="#toc23" tabindex="0">まとめ: Pandas MultiIndex を使いこなしてデータ分析を効率化</a><ol><li><a href="#toc24" tabindex="0">次のステップ</a></li><li><a href="#toc25" tabindex="0">関連記事</a></li><li><a href="#toc26" tabindex="0">MultiIndexとは何ですか？</a></li><li><a href="#toc27" tabindex="0">MultiIndexを作成する方法は？</a></li><li><a href="#toc28" tabindex="0">stack/unstackの役割は？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">Pandas MultiIndex (階層型インデックス) の作成方法とサンプルデータ</span></h2>
<h3><span id="toc2">サンプルデータの作成</span></h3>
<pre class="language-python" data-prismjs-copy><code class="language-python">
import pandas as pd
</code></pre>
<pre class="language-python" data-prismjs-copy><code class="language-python">
sales_data = {
    '月': ['2023-01', '2023-01', '2023-01', '2023-02', '2023-02', '2023-02', '2023-03', '2023-03','2023-03'],
    '店舗': ['A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A'],
    '商品': ['りんご', 'バナナ', 'りんご', 'バナナ', 'りんご', 'バナナ', 'りんご', 'バナナ', 'バナナ'],
    '売上（円）': [1000, 800, 1200, 900, 1100, 850, 1300, 950, 850],
    '売上原価（円）': [700, 500, 700, 600, 700, 400, 700, 550, 500]
}
sales_df = pd.DataFrame(sales_data)
display(sales_df)
</code></pre>

  <div id="df-ee5b1021-2339-4f18-856a-60cfbae28677" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>月</th>
      <th>店舗</th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>2023-01</td>
      <td>A</td>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2023-01</td>
      <td>A</td>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2023-01</td>
      <td>B</td>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2023-02</td>
      <td>B</td>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>4</th>
      <td>2023-02</td>
      <td>A</td>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>5</th>
      <td>2023-02</td>
      <td>A</td>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th>6</th>
      <td>2023-03</td>
      <td>B</td>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>7</th>
      <td>2023-03</td>
      <td>B</td>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>8</th>
      <td>2023-03</td>
      <td>A</td>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-ee5b1021-2339-4f18-856a-60cfbae28677')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-ee5b1021-2339-4f18-856a-60cfbae28677 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ee5b1021-2339-4f18-856a-60cfbae28677');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-edfa0d27-1501-4d3e-b4db-67904dd65d72">
      <button class="colab-df-quickchart" onclick="quickchart('df-edfa0d27-1501-4d3e-b4db-67904dd65d72')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-edfa0d27-1501-4d3e-b4db-67904dd65d72 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_85b45709-9361-400b-ab6f-8f211413a6bd">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_85b45709-9361-400b-ab6f-8f211413a6bd button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<h3><span id="toc3">行方向への階層型インデックス（pandas MultiIndex）の設定 (set_index)</span></h3>
<p>階層型インデックス、すなわち pandas MultiIndex を設定することで、複数のカテゴリを組み合わせてデータを整理し、後の分析や絞り込みを効率的に行えるようになります。ここでは、&#8217;月&#8217;と&#8217;店舗&#8217;を組み合わせて行の pandas MultiIndex とします。</p>
<p><code>set_index()</code> メソッドに、pandas MultiIndex として設定したい列名のリストを渡すことで、階層型インデックスを持つ DataFrame を作成できます。元の列はインデックスに移動し、データ本体からは削除されます。</p>
<p>以下のコードを実行して、<code>sales_df</code> に pandas MultiIndex を適用した <code>sales_hier_df</code> を見てみましょう。行のインデックス部分が「月」と「店舗」の 2 つのレベルで構成されているのが分かります。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
# '月'と'店舗'を階層型インデックスに設定
sales_hier_df = sales_df.set_index(['月', '店舗'])
display(sales_hier_df)
</code></pre>

  <div id="df-e295bf0e-eb87-4273-bf8c-bc4e5a23be69" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-e295bf0e-eb87-4273-bf8c-bc4e5a23be69')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-e295bf0e-eb87-4273-bf8c-bc4e5a23be69 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-e295bf0e-eb87-4273-bf8c-bc4e5a23be69');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-77cfc9fc-5030-47c3-b1a6-08a455a35d05">
      <button class="colab-df-quickchart" onclick="quickchart('df-77cfc9fc-5030-47c3-b1a6-08a455a35d05')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-77cfc9fc-5030-47c3-b1a6-08a455a35d05 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_53c4fafa-9a50-41f3-8ffb-cfa1abf89e0f">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_53c4fafa-9a50-41f3-8ffb-cfa1abf89e0f button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<h2><span id="toc4">Pandas MultiIndex DataFrame からのデータ選択・絞り込み (loc, iloc)</span></h2>
<h3><span id="toc5">特定の列（カラム）の選択</span></h3>
<h4><span id="toc6">単一列の選択</span></h4>
<p>pandas MultiIndex を持つ DataFrame から、特定の列を選択するのは通常の DataFrame と同じように行えます。ここでは例として、&#8217;商品&#8217;列のみを絞り込んで表示してみましょう。</p>
<p>列を一つだけ選択する場合は、DataFrame 名の後に角括弧 <code>[]</code> で列名を指定します。結果は Series として返されます。</p>
<p>以下のコードを実行すると、元の DataFrame と比較して、「商品」列だけが抽出された Series が表示されます。インデックスは pandas MultiIndex (<code>月</code>, <code>店舗</code>) がそのまま引き継がれていることが分かります。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('絞り込み後')
# グループの絞り込み
display(sales_hier_df['商品'])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-514fadbc-a77f-47fb-a558-1198cd7b5567" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-514fadbc-a77f-47fb-a558-1198cd7b5567')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-514fadbc-a77f-47fb-a558-1198cd7b5567 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-514fadbc-a77f-47fb-a558-1198cd7b5567');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-a77ae6cc-17bd-48f9-93e5-ce8ac09e9830">
      <button class="colab-df-quickchart" onclick="quickchart('df-a77ae6cc-17bd-48f9-93e5-ce8ac09e9830')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-a77ae6cc-17bd-48f9-93e5-ce8ac09e9830 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_b0dc3b71-4fa0-46b7-bea3-c19096d6356c">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_b0dc3b71-4fa0-46b7-bea3-c19096d6356c button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>絞り込み後
</pre>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
    </tr>
  </tbody>
</table>
</div><br><label><b>dtype:</b> object</label>
<p>なお、</p>
<p><code>`</code></p>
<p>sales_hier_df.loc[:,&#8217;商品&#8217;]</p>
<p><code>`</code></p>
<p>にしても同じ結果が返ります。</p>
<h4><span id="toc7">複数列の選択</span></h4>
<p>複数の列を選択したい場合は、列名のリストを角括弧 <code>[]</code> の中に指定します。結果は DataFrame として返されます。ここでは例として、&#8217;商品&#8217;列と&#8217;売上（円）&#8217;列を同時に絞り込んで表示してみましょう。</p>
<p>以下のコードを実行すると、元の DataFrame から「商品」と「売上（円）」の 2 つの列だけが抽出された DataFrame が表示されます。行の階層型インデックス (<code>月</code>, <code>店舗</code>) は維持されています。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('絞り込み後')
# グループの絞り込み
display(sales_hier_df[['商品','売上（円）']])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-f4e20075-6520-4aae-9f53-be99779d2f9d" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-f4e20075-6520-4aae-9f53-be99779d2f9d')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-f4e20075-6520-4aae-9f53-be99779d2f9d button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-f4e20075-6520-4aae-9f53-be99779d2f9d');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-2c9cf78b-e592-4309-9896-34e2187c2659">
      <button class="colab-df-quickchart" onclick="quickchart('df-2c9cf78b-e592-4309-9896-34e2187c2659')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-2c9cf78b-e592-4309-9896-34e2187c2659 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_322116d0-cede-4c32-b292-9ca06fab3baa">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_322116d0-cede-4c32-b292-9ca06fab3baa button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>絞り込み後
</pre>

  <div id="df-2612edca-9c75-4c5b-a32a-56fc592ea131" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-2612edca-9c75-4c5b-a32a-56fc592ea131')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-2612edca-9c75-4c5b-a32a-56fc592ea131 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-2612edca-9c75-4c5b-a32a-56fc592ea131');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-ff1163f1-d395-4a58-9981-d55b34b3ad80">
      <button class="colab-df-quickchart" onclick="quickchart('df-ff1163f1-d395-4a58-9981-d55b34b3ad80')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-ff1163f1-d395-4a58-9981-d55b34b3ad80 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<p>なお、</p>
<p><code>`</code></p>
<p>sales_hier_df.loc[:,[&#8216;商品&#8217;,&#8217;売上（円）&#8217;]]</p>
<p><code>`</code></p>
<p>にしても同じ結果が返ります。</p>
<h3><span id="toc8">特定の行の位置による選択 (.iloc)</span></h3>
<p>pandas MultiIndex を持つ DataFrame から特定の行を選択するにはいくつかの方法があります。ここでは、行の<strong>位置</strong>（0 から始まる整数）を使って絞り込む方法を見てみましょう。<code>.iloc</code> アクセサを使用します。</p>
<p>スライスを使うことで、特定の範囲の行を選択できます。例えば、最初の 1 行を選択するには <code>iloc[0:1]</code> と指定します。これは、0 番目の行を含み、1 番目の行を含まない範囲を指定していることになります。</p>
<p>位置による選択は、データの物理的な並び順に基づいて行を選択したい場合に便利です。以下のコードでは、最初の 1 行目を取得しています。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('絞り込み後')
# グループの絞り込み
display(sales_hier_df[0:1])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-a06459c8-04c6-4615-825a-d2d492f107f1" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-a06459c8-04c6-4615-825a-d2d492f107f1')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-a06459c8-04c6-4615-825a-d2d492f107f1 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-a06459c8-04c6-4615-825a-d2d492f107f1');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-564f50d6-87d0-4e1f-8a88-8168b13a71b3">
      <button class="colab-df-quickchart" onclick="quickchart('df-564f50d6-87d0-4e1f-8a88-8168b13a71b3')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-564f50d6-87d0-4e1f-8a88-8168b13a71b3 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_7361b3f0-79fb-44d1-bf75-f7a65b925c6f">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_7361b3f0-79fb-44d1-bf75-f7a65b925c6f button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>絞り込み後
</pre>

  <div id="df-ee1a70c7-9a00-4c87-acc8-677a3395ccb0" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-ee1a70c7-9a00-4c87-acc8-677a3395ccb0')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-ee1a70c7-9a00-4c87-acc8-677a3395ccb0 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ee1a70c7-9a00-4c87-acc8-677a3395ccb0');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    </div>
  </div>

<p>また、２番目の行のデータを見たいならば、</p>
<p><code>`</code></p>
<p>sales_hier_df[2:3]</p>
<p><code>`</code></p>
<p>にすると、グループの絞り込みができます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('絞り込み後')
# グループの絞り込み
display(sales_hier_df[2:3])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-ac9accfc-27d3-4f84-98f9-a4a1579e4742" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-ac9accfc-27d3-4f84-98f9-a4a1579e4742')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-ac9accfc-27d3-4f84-98f9-a4a1579e4742 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ac9accfc-27d3-4f84-98f9-a4a1579e4742');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-db60d182-c33a-4af6-a69d-c506ff0752e9">
      <button class="colab-df-quickchart" onclick="quickchart('df-db60d182-c33a-4af6-a69d-c506ff0752e9')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-db60d182-c33a-4af6-a69d-c506ff0752e9 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_4d049cba-4feb-4175-9c23-694f19c3b4b5">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_4d049cba-4feb-4175-9c23-694f19c3b4b5 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>絞り込み後
</pre>

  <div id="df-b0c2aa5a-802a-45f5-bd82-5507c16cd4b5" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2023-01</th>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-b0c2aa5a-802a-45f5-bd82-5507c16cd4b5')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-b0c2aa5a-802a-45f5-bd82-5507c16cd4b5 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-b0c2aa5a-802a-45f5-bd82-5507c16cd4b5');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    </div>
  </div>

<h2><span id="toc9">階層型インデックス（pandas MultiIndex）を使ったラベルによるデータの選択・絞り込み (.loc)</span></h2>
<p>特定の行（インデックスラベル）を選択する際には、<code>.loc</code> アクセサを使用します。pandas MultiIndex では、この <code>.loc</code> を使って柔軟な絞り込みが可能です。</p>
<h3><span id="toc10">複数レベルのインデックスラベルによる特定の組み合わせの選択</span></h3>
<p>例えば、「2023 年 1 月の A 店」のように、pandas MultiIndex の複数レベル（&#8217;月&#8217;と&#8217;店舗&#8217;）の特定の組み合わせに一致する行を絞り込みたい場合、<code>.loc</code>にタプルで指定します。</p>
<p>以下のコードを実行すると、<code>('2023-01', 'A')</code> のラベルに一致する行が抽出されます。この場合、2023 年 1 月の A 店のデータがすべて表示されます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('特定の月と店舗で絞り込み (例: 2023-01 の A 店)')
display(sales_hier_df.loc[('2023-01', 'A')])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-210907b3-a09d-4817-8d5c-050efccbeb7d" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-210907b3-a09d-4817-8d5c-050efccbeb7d')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-210907b3-a09d-4817-8d5c-050efccbeb7d button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-210907b3-a09d-4817-8d5c-050efccbeb7d');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-0c67fe48-54ff-4ce6-9eed-801b54ff8dda">
      <button class="colab-df-quickchart" onclick="quickchart('df-0c67fe48-54ff-4ce6-9eed-801b54ff8dda')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-0c67fe48-54ff-4ce6-9eed-801b54ff8dda button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_0b1ba9a4-a96f-4082-ae5b-b91a70ceb718">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_0b1ba9a4-a96f-4082-ae5b-b91a70ceb718 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>特定の月と店舗で絞り込み (例: 2023-01 の A 店)
</pre>
<pre>/tmp/ipython-input-1872768620.py:5: PerformanceWarning: indexing past lexsort depth may impact performance.
  display(sales_hier_df.loc[('2023-01', 'A')])
</pre>

  <div id="df-24963cae-d0f4-4bad-8aa2-bca8db453226" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-24963cae-d0f4-4bad-8aa2-bca8db453226')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-24963cae-d0f4-4bad-8aa2-bca8db453226 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-24963cae-d0f4-4bad-8aa2-bca8db453226');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-41fed59e-5c25-4735-8c68-5ff13f46a3e1">
      <button class="colab-df-quickchart" onclick="quickchart('df-41fed59e-5c25-4735-8c68-5ff13f46a3e1')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-41fed59e-5c25-4735-8c68-5ff13f46a3e1 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h3><span id="toc11">複数レベルにまたがる要素の選択 (slice(None)の活用)</span></h3>
<p>特定のレベルの全ての要素を選択しつつ、別のレベルで絞り込みたい場合は、<code>slice(None)</code> を使用します。例えば、全ての月の&#8217;A&#8217;店のデータを取得するには <code>.loc[(slice(None), 'A'), :]</code> と指定します。<code>slice(None)</code> はそのレベルの全ての要素を選択することを意味します。</p>
<p>以下のコードを実行すると、月のレベルは全て選択し、店舗レベルで &#8216;A&#8217; を選択したデータが表示されます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('特定の店舗で絞り込み (例: A 店の全ての月)')
display(sales_hier_df.loc[(slice(None), 'A'), :])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-93cc3668-3f67-496e-bd95-536a1cb336b9" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-93cc3668-3f67-496e-bd95-536a1cb336b9')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-93cc3668-3f67-496e-bd95-536a1cb336b9 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-93cc3668-3f67-496e-bd95-536a1cb336b9');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-bbfb3c27-7c86-4779-9f7e-84b39ab109da">
      <button class="colab-df-quickchart" onclick="quickchart('df-bbfb3c27-7c86-4779-9f7e-84b39ab109da')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-bbfb3c27-7c86-4779-9f7e-84b39ab109da button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_9a7602b2-fef6-46f9-a310-174575d3a48b">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_9a7602b2-fef6-46f9-a310-174575d3a48b button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>特定の店舗で絞り込み (例: A 店の全ての月)
</pre>

  <div id="df-81ad1e0c-0989-4cc2-9cc3-490602d3bf25" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th rowspan="2" valign="top">2023-02</th>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th>2023-03</th>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-81ad1e0c-0989-4cc2-9cc3-490602d3bf25')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-81ad1e0c-0989-4cc2-9cc3-490602d3bf25 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-81ad1e0c-0989-4cc2-9cc3-490602d3bf25');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-cb540b23-d395-45ca-b6cb-28a383610c94">
      <button class="colab-df-quickchart" onclick="quickchart('df-cb540b23-d395-45ca-b6cb-28a383610c94')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-cb540b23-d395-45ca-b6cb-28a383610c94 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h3><span id="toc12">単一レベルのインデックスラベルによる選択</span></h3>
<p><code>.loc</code> を使用すると、pandas MultiIndex の特定のレベルのラベルを指定して行を選択できます。例えば、最初のレベルである &#8216;月&#8217; のラベルを指定して、特定の月のデータを全て選択することができます。</p>
<p>また、特定の行（インデックスラベル）と特定の列（カラム名）を組み合わせて絞り込むことも可能です。<code>.loc[行の指定, 列の指定]</code> の形式で記述します。</p>
<p>ここではたとえば、&#8217;2023-01&#8217;の全ての店舗のデータから、&#8217;商品&#8217;列だけを見たいとしましょう。行の指定には <code>'2023-01'</code> を、列の指定には <code>'商品'</code> を使います。単一レベルのラベルを指定する場合は、タプルではなく直接ラベル名を指定するか、単一要素のタプル <code>('2023-01',)</code> とします。</p>
<p>以下のコードを実行すると、2023 年 1 月の全ての店舗のデータの中から、「商品」列だけが抽出されます。結果は Series として表示されます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('絞り込み前')
display(sales_hier_df)

print('絞り込み後（2023-01の全店舗の商品列を絞り込み）')
# 行の指定にタプル ('2023-01',) を使い、列の指定に '商品' を使う
display(sales_hier_df.loc[('2023-01',), '商品'])
</code></pre>
<pre>絞り込み前
</pre>

  <div id="df-ef1bd756-5184-49ce-8fd6-184b775a9391" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-ef1bd756-5184-49ce-8fd6-184b775a9391')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-ef1bd756-5184-49ce-8fd6-184b775a9391 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ef1bd756-5184-49ce-8fd6-184b775a9391');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-5390efda-7132-4439-b17a-a5dbd4e78336">
      <button class="colab-df-quickchart" onclick="quickchart('df-5390efda-7132-4439-b17a-a5dbd4e78336')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-5390efda-7132-4439-b17a-a5dbd4e78336 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_151eaa96-1fb4-43bd-91ee-3651f4bc4445">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_151eaa96-1fb4-43bd-91ee-3651f4bc4445 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>絞り込み後（2023-01の全店舗の商品列を絞り込み）
</pre>
<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>商品</th>
    </tr>
    <tr>
      <th>店舗</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>A</th>
      <td>りんご</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
    </tr>
  </tbody>
</table>
</div><br><label><b>dtype:</b> object</label>
<h3><span id="toc13">.loc使用時のパフォーマンスに関する注意点 (PerformanceWarningとsort_index)</span></h3>
<p>pandas MultiIndex を持つ DataFrame で <code>.loc</code> アクセサを使ってラベルによる絞り込みを行う際に、時折 <code>PerformanceWarning</code> が表示されることがあります。これは、特にインデックスがソートされていない場合に発生し、データの検索効率が低下する可能性があることを示しています。</p>
<p><strong>この <code>PerformanceWarning</code> は、pandas MultiIndex を扱う上でよく遭遇するものであり、インデックスがソートされていない状態で特定のラベルやスライスによる選択を行う際に発生します。</strong></p>
<p>Pandas は、ソートされたインデックスに対しては非常に高速な検索アルゴリズムを使用できますが、ソートされていない場合は、各インデックスエントリを個別にチェックする必要があり、特に大規模なデータでは処理時間が長くなることがあります。</p>
<p>このパフォーマンスの問題を解決し、<code>PerformanceWarning</code> を回避するためには、<code>.loc</code> を使用して絞り込みを行う前に、DataFrame のインデックスを <code>sort_index()</code> メソッドでソートすることが推奨されます。<code>sort_index()</code> は、インデックスの各レベルを順番にソートし、効率的なデータアクセスを可能にします。</p>
<p><strong>したがって、pandas MultiIndex を使った <code>.loc</code> によるデータ選択を行う際は、事前に <code>sort_index()</code> を実行することが、パフォーマンスを最適化し、警告を回避するための標準的なプラクティスとなります。</strong></p>
<p>ソートされたインデックスを持つ DataFrame では、特定のラベルやスライスによる <code>.loc</code> での選択が高速化され、警告も表示されなくなります。</p>
<p>以下のコードでは、まずソート前の DataFrame で特定の絞り込みを行い、<code>PerformanceWarning</code> が表示される場合があることを確認します。次に、インデックスをソートした DataFrame で同じ絞り込みを行い、警告が表示されないこと、および結果が変わらないことを確認します。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('ソート前')
display(sales_hier_df)

# インデックスをソート
sales_hier_sorted_df = sales_hier_df.sort_index()

print('インデックスをソート後')
display(sales_hier_sorted_df)

print('ソート済みDataFrameで特定の月と店舗で絞り込み (例: 2023-01 の A 店)')
display(sales_hier_sorted_df.loc[('2023-01', 'A')])

print('ソート済みDataFrameで特定の店舗で絞り込み (例: A 店の全ての月)')
display(sales_hier_sorted_df.loc[(slice(None), 'A'), :])
</code></pre>
<pre>ソート前
</pre>

  <div id="df-e8e79a10-b6e9-49e5-bccc-60ef837b723a" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-e8e79a10-b6e9-49e5-bccc-60ef837b723a')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-e8e79a10-b6e9-49e5-bccc-60ef837b723a button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-e8e79a10-b6e9-49e5-bccc-60ef837b723a');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-53785a63-6980-4bab-a5e0-6e67360e7350">
      <button class="colab-df-quickchart" onclick="quickchart('df-53785a63-6980-4bab-a5e0-6e67360e7350')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-53785a63-6980-4bab-a5e0-6e67360e7350 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_6a516ddf-6882-4f22-9f91-cdf075f46c63">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_6a516ddf-6882-4f22-9f91-cdf075f46c63 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>インデックスをソート後
</pre>

  <div id="df-87758a97-004d-4bee-a85c-65cca4bdfb97" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-87758a97-004d-4bee-a85c-65cca4bdfb97')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-87758a97-004d-4bee-a85c-65cca4bdfb97 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-87758a97-004d-4bee-a85c-65cca4bdfb97');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-e67bf601-7a79-4e68-b1dc-bb137905fdff">
      <button class="colab-df-quickchart" onclick="quickchart('df-e67bf601-7a79-4e68-b1dc-bb137905fdff')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-e67bf601-7a79-4e68-b1dc-bb137905fdff button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_f1274bd3-6a5a-4561-8694-13cd44531d0b">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_sorted_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_f1274bd3-6a5a-4561-8694-13cd44531d0b button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_sorted_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>ソート済みDataFrameで特定の月と店舗で絞り込み (例: 2023-01 の A 店)
</pre>

  <div id="df-81d1211c-cd02-4af7-81af-8b48f0ac8e39" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-81d1211c-cd02-4af7-81af-8b48f0ac8e39')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-81d1211c-cd02-4af7-81af-8b48f0ac8e39 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-81d1211c-cd02-4af7-81af-8b48f0ac8e39');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-d96fd346-61b6-4907-ab49-c6be3ee40354">
      <button class="colab-df-quickchart" onclick="quickchart('df-d96fd346-61b6-4907-ab49-c6be3ee40354')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-d96fd346-61b6-4907-ab49-c6be3ee40354 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<pre>ソート済みDataFrameで特定の店舗で絞り込み (例: A 店の全ての月)
</pre>

  <div id="df-9e617980-0c92-4f18-b215-a7b83266001b" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th rowspan="2" valign="top">2023-02</th>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th>2023-03</th>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-9e617980-0c92-4f18-b215-a7b83266001b')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-9e617980-0c92-4f18-b215-a7b83266001b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-9e617980-0c92-4f18-b215-a7b83266001b');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-1a065139-8728-4245-b453-eba0b9c90a94">
      <button class="colab-df-quickchart" onclick="quickchart('df-1a065139-8728-4245-b453-eba0b9c90a94')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-1a065139-8728-4245-b453-eba0b9c90a94 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h2><span id="toc14">Pandas MultiIndex を使った高度なデータ抽出・絞り込み</span></h2>
<p>pandas MultiIndex の強力な点は、単一のレベルだけでなく、複数のレベルを組み合わせてデータを柔軟に絞り込めることです。<code>.loc</code>を使用することで、インデックスの特定の組み合わせや、特定のレベルのすべての要素を選択しながら別のレベルで絞り込むといった、より複雑な条件でのデータ抽出が容易になります。</p>
<h3><span id="toc15">特定の月と店舗のデータを絞り込む</span></h3>
<p>例えば、「2023 年 2 月の A 店」のように、pandas MultiIndex の複数レベル（&#8217;月&#8217;と&#8217;店舗&#8217;）の特定の組み合わせに一致する行を絞り込みたい場合、<code>.loc</code>にタプルで指定します。</p>
<p>以下のコードを実行すると、2023 年 2 月の A 店のデータのみが抽出されます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('階層型インデックスDataFrame')
display(sales_hier_df)

print("特定の月 ('2023-02') かつ特定の店舗 ('A') のデータを絞り込み:")
display(sales_hier_df.loc[('2023-02', 'A')])

print("特定の月 ('2023-03') における特定の商品のデータ ('バナナ') を全ての店舗で絞り込み:")
display(sales_hier_df.loc[(slice(None), slice(None)), :][sales_hier_df['商品'] == 'バナナ'].loc['2023-03'])
</code></pre>
<pre>階層型インデックスDataFrame
</pre>

  <div id="df-c1f76cad-2c9c-4250-8eb1-f0573eb13c09" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-c1f76cad-2c9c-4250-8eb1-f0573eb13c09')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-c1f76cad-2c9c-4250-8eb1-f0573eb13c09 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-c1f76cad-2c9c-4250-8eb1-f0573eb13c09');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-eab6596d-7503-4504-acda-3ddc82b3aa50">
      <button class="colab-df-quickchart" onclick="quickchart('df-eab6596d-7503-4504-acda-3ddc82b3aa50')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-eab6596d-7503-4504-acda-3ddc82b3aa50 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_38258474-3f1a-40f6-8102-522e4332f638">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_38258474-3f1a-40f6-8102-522e4332f638 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>特定の月 ('2023-02') かつ特定の店舗 ('A') のデータを絞り込み:
</pre>
<pre>/tmp/ipython-input-3881532412.py:5: PerformanceWarning: indexing past lexsort depth may impact performance.
  display(sales_hier_df.loc[('2023-02', 'A')])
</pre>

  <div id="df-36cacea2-814f-4033-a838-a81cd03413ab" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-02</th>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-36cacea2-814f-4033-a838-a81cd03413ab')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-36cacea2-814f-4033-a838-a81cd03413ab button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-36cacea2-814f-4033-a838-a81cd03413ab');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-fa72b98b-a5a2-470b-b7ab-179e2c69450d">
      <button class="colab-df-quickchart" onclick="quickchart('df-fa72b98b-a5a2-470b-b7ab-179e2c69450d')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-fa72b98b-a5a2-470b-b7ab-179e2c69450d button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<pre>特定の月 ('2023-03') における特定の商品のデータ ('バナナ') を全ての店舗で絞り込み:
</pre>

  <div id="df-14451989-c889-4c97-9acd-01be25302584" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-14451989-c889-4c97-9acd-01be25302584')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-14451989-c889-4c97-9acd-01be25302584 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-14451989-c889-4c97-9acd-01be25302584');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-5fc20d71-10eb-4f1a-bd3b-68bd2750ff1a">
      <button class="colab-df-quickchart" onclick="quickchart('df-5fc20d71-10eb-4f1a-bd3b-68bd2750ff1a')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-5fc20d71-10eb-4f1a-bd3b-68bd2750ff1a button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h2><span id="toc16">Pandas MultiIndex でのデータ集計 (groupby level)</span></h2>
<p>pandas MultiIndex を設定することで、特定のインデックスレベルを基準にしてデータを簡単に集計できます。<code>groupby()</code> メソッドと <code>level</code> 引数を使うことで、指定したレベルでデータをグループ化し、合計や平均などの集計関数を適用できます。</p>
<p>以下の例では、様々な pandas MultiIndex レベルを軸に売上と売上原価の合計を計算しています。集計対象から文字列型の&#8217;商品&#8217;列を除外するために、数値列のみを選択して集計しています。</p>
<h3><span id="toc17">単一インデックスレベルでの集計 (例: 店舗別)</span></h3>
<p>&#8216;店舗&#8217;を軸に売上と売上原価の合計を計算します。<code>groupby(level='店舗')</code> で店舗ごとにデータをグループ化し、<code>.sum()</code> で各グループの合計値を計算しています。集計結果からは、例えば「A 店の総売上は〇〇円、B 店の総売上は△△円である」といった情報を読み取ることができます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('合計前')
display(sales_hier_df)

print('店舗ごとの合計')
display(sales_hier_df.groupby(level= '店舗', axis = 0).sum())

print('店舗ごとの合計（商品を除く)')
display(sales_hier_df[['売上（円）','売上原価（円）']].groupby(level= '店舗', axis = 0).sum())
</code></pre>
<pre>合計前
</pre>

  <div id="df-978d2e48-7f14-4365-bb87-ef3dafad1360" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-978d2e48-7f14-4365-bb87-ef3dafad1360')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-978d2e48-7f14-4365-bb87-ef3dafad1360 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-978d2e48-7f14-4365-bb87-ef3dafad1360');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-067ade19-0729-4420-a2b3-8b196218428c">
      <button class="colab-df-quickchart" onclick="quickchart('df-067ade19-0729-4420-a2b3-8b196218428c')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-067ade19-0729-4420-a2b3-8b196218428c button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_e2b2a7f4-f20e-421b-8f25-1669671fd8fa">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_e2b2a7f4-f20e-421b-8f25-1669671fd8fa button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>店舗ごとの合計
</pre>
<pre>/tmp/ipython-input-3547325012.py:5: FutureWarning: The 'axis' keyword in DataFrame.groupby is deprecated and will be removed in a future version.
  display(sales_hier_df.groupby(level= '店舗', axis = 0).sum())
</pre>

  <div id="df-472724ff-51cc-4def-9022-e558c8776e4a" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>A</th>
      <td>りんごバナナりんごバナナバナナ</td>
      <td>4600</td>
      <td>2800</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんごバナナりんごバナナ</td>
      <td>4350</td>
      <td>2550</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-472724ff-51cc-4def-9022-e558c8776e4a')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-472724ff-51cc-4def-9022-e558c8776e4a button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-472724ff-51cc-4def-9022-e558c8776e4a');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-0e39471a-36f7-451e-8d58-9cec67ad3eef">
      <button class="colab-df-quickchart" onclick="quickchart('df-0e39471a-36f7-451e-8d58-9cec67ad3eef')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-0e39471a-36f7-451e-8d58-9cec67ad3eef button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<pre>店舗ごとの合計（商品を除く)
</pre>
<pre>/tmp/ipython-input-3547325012.py:8: FutureWarning: The 'axis' keyword in DataFrame.groupby is deprecated and will be removed in a future version.
  display(sales_hier_df[['売上（円）','売上原価（円）']].groupby(level= '店舗', axis = 0).sum())
</pre>

  <div id="df-1a301198-936f-40a4-912c-3252787b3103" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>店舗</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>A</th>
      <td>4600</td>
      <td>2800</td>
    </tr>
    <tr>
      <th>B</th>
      <td>4350</td>
      <td>2550</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-1a301198-936f-40a4-912c-3252787b3103')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-1a301198-936f-40a4-912c-3252787b3103 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-1a301198-936f-40a4-912c-3252787b3103');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-85d5fbd3-c11b-4201-b027-2f3990cff300">
      <button class="colab-df-quickchart" onclick="quickchart('df-85d5fbd3-c11b-4201-b027-2f3990cff300')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-85d5fbd3-c11b-4201-b027-2f3990cff300 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h4><span id="toc18">【補足】groupbyのaxis引数に関する警告について</span></h4>
<p>上記のコードを実行すると、FutureWarning: The &#8216;axis&#8217; keyword in DataFrame.groupby is deprecated and will be removed in a future version. という警告が表示されることがあります。これは、将来的にgroupbyメソッドでaxisを使う方法が廃止される可能性があることを示しています。</p>
<p>現在（pandas の特定のバージョン）ではまだ動作しますが、将来的な互換性を考慮すると、axis=0の場合は引数を省略するか、列方向の集計（axis=1）の場合は groupby(level=&#8217;color&#8217;, axis=1) の代わりに、データの持ち方によっては先にデータを転置（.T）してからgroupbyを行うなどの代替手段を検討することもできます。</p>
<p>なお、groupbyメソッドでaxis=0を指定することは、デフォルトの動作である「行方向（インデックス）でのグループ化」を明示していることになります。このため、通常はaxis=0を省略しても同じ結果が得られます。警告を避けるためにも、行方向のグループ化の場合はaxis引数を省略することが推奨されます。</p>
<h3><span id="toc19">単一インデックスレベルでの集計 (例: 月別)</span></h3>
<p>次に、&#8217;月&#8217;を軸に売上と売上原価の合計を計算してみましょう。<code>groupby(level='月')</code> を使用します。これにより、月ごとの全体の売上動向を把握できます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('合計前')
display(sales_hier_df)

print('月ごとの合計')
# 警告を避けるため、axis=0 は省略
display(sales_hier_df[['売上（円）','売上原価（円）']].groupby(level= ['月']).sum())
</code></pre>
<pre>合計前
</pre>

  <div id="df-be005521-f341-4383-b080-96d01fa1efb0" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-be005521-f341-4383-b080-96d01fa1efb0')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-be005521-f341-4383-b080-96d01fa1efb0 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-be005521-f341-4383-b080-96d01fa1efb0');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-059ce6b4-caa8-494a-b25f-00d6bbf70791">
      <button class="colab-df-quickchart" onclick="quickchart('df-059ce6b4-caa8-494a-b25f-00d6bbf70791')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-059ce6b4-caa8-494a-b25f-00d6bbf70791 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_deef470d-9fc9-488d-8879-09804f843b3f">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_deef470d-9fc9-488d-8879-09804f843b3f button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>月ごとの合計
</pre>

  <div id="df-3ea9377a-58c3-442a-8bed-c5cd26a02059" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>2023-01</th>
      <td>3000</td>
      <td>1900</td>
    </tr>
    <tr>
      <th>2023-02</th>
      <td>2850</td>
      <td>1700</td>
    </tr>
    <tr>
      <th>2023-03</th>
      <td>3100</td>
      <td>1750</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-3ea9377a-58c3-442a-8bed-c5cd26a02059')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-3ea9377a-58c3-442a-8bed-c5cd26a02059 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-3ea9377a-58c3-442a-8bed-c5cd26a02059');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-03c33d58-22ac-4613-b2e3-e794711c92a3">
      <button class="colab-df-quickchart" onclick="quickchart('df-03c33d58-22ac-4613-b2e3-e794711c92a3')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-03c33d58-22ac-4613-b2e3-e794711c92a3 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h3><span id="toc20">複数インデックスレベルでの集計 (例: 月と店舗別)</span></h3>
<p>さらに、&#8217;月&#8217;と&#8217;店舗&#8217;の両方を軸にして集計することも可能です。<code>groupby(level=['月', '店舗'])</code> のようにレベル名のリストを指定します。これにより、各月における各店舗の合計売上を詳細に分析できます。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('合計前')
display(sales_hier_df)

print('月と店舗ごとの合計')
# 警告を避けるため、axis=0 は省略
display(sales_hier_df[['売上（円）','売上原価（円）']].groupby(level= ['月', '店舗']).sum())
</code></pre>
<pre>合計前
</pre>

  <div id="df-779398bf-1d8e-4703-b5d7-b6313654aadd" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-779398bf-1d8e-4703-b5d7-b6313654aadd')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-779398bf-1d8e-4703-b5d7-b6313654aadd button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-779398bf-1d8e-4703-b5d7-b6313654aadd');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-2d5b62c5-69ab-41e3-b9c9-1355366342a6">
      <button class="colab-df-quickchart" onclick="quickchart('df-2d5b62c5-69ab-41e3-b9c9-1355366342a6')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-2d5b62c5-69ab-41e3-b9c9-1355366342a6 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_75802701-705c-40af-8332-1531dde30494">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_75802701-705c-40af-8332-1531dde30494 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>月と店舗ごとの合計
</pre>

  <div id="df-cf4609f1-0b80-4aa3-a48f-ce41b816722b" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="2" valign="top">2023-01</th>
      <th>A</th>
      <td>1800</td>
      <td>1200</td>
    </tr>
    <tr>
      <th>B</th>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="2" valign="top">2023-02</th>
      <th>A</th>
      <td>1950</td>
      <td>1100</td>
    </tr>
    <tr>
      <th>B</th>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th rowspan="2" valign="top">2023-03</th>
      <th>A</th>
      <td>850</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>2250</td>
      <td>1250</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-cf4609f1-0b80-4aa3-a48f-ce41b816722b')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-cf4609f1-0b80-4aa3-a48f-ce41b816722b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-cf4609f1-0b80-4aa3-a48f-ce41b816722b');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-dd6244bd-97c9-4241-aced-338027c6a193">
      <button class="colab-df-quickchart" onclick="quickchart('df-dd6244bd-97c9-4241-aced-338027c6a193')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-dd6244bd-97c9-4241-aced-338027c6a193 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h2><span id="toc21">MultiIndex のリセットと削除</span></h2>
<p>pandas MultiIndex を持つ DataFrame から特定の行を削除したい場合は、<code>drop()</code> メソッドを使います。<code>drop()</code> に削除したいインデックスのラベルを指定します。階層型インデックスの場合は、削除したいレベルのラベルを指定します。</p>
<p>次の例では、月レベルのインデックスである&#8217;2023-03&#8217;に対応する全ての行を削除しています。これにより、特定の期間のデータを分析から除外したい場合などに便利です。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('削除前')
display(sales_hier_df)

print('2023-03行を削除後')
display(sales_hier_df.drop(['2023-03']))
</code></pre>
<pre>削除前
</pre>

  <div id="df-0b778a9f-ac0a-4916-8aa2-d03525aeacfa" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-0b778a9f-ac0a-4916-8aa2-d03525aeacfa')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-0b778a9f-ac0a-4916-8aa2-d03525aeacfa button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-0b778a9f-ac0a-4916-8aa2-d03525aeacfa');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-29781cd4-0726-4dd6-84fb-714d1f538e15">
      <button class="colab-df-quickchart" onclick="quickchart('df-29781cd4-0726-4dd6-84fb-714d1f538e15')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-29781cd4-0726-4dd6-84fb-714d1f538e15 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_6577a334-a7b9-467e-b0e5-9f9026e09018">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_6577a334-a7b9-467e-b0e5-9f9026e09018 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>2023-03行を削除後
</pre>

  <div id="df-20221ee5-deb8-4f3e-9a70-d587895f80df" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-20221ee5-deb8-4f3e-9a70-d587895f80df')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-20221ee5-deb8-4f3e-9a70-d587895f80df button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-20221ee5-deb8-4f3e-9a70-d587895f80df');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-b21ef3bd-da83-4c0a-b53d-94b7c6f98b5e">
      <button class="colab-df-quickchart" onclick="quickchart('df-b21ef3bd-da83-4c0a-b53d-94b7c6f98b5e')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-b21ef3bd-da83-4c0a-b53d-94b7c6f98b5e button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

    </div>
  </div>

<h3><span id="toc22">階層型インデックス（pandas MultiIndex）のリセット (reset_index)</span></h3>
<p>pandas MultiIndex を設定した DataFrame を、元のフラットなインデックスに戻したい場合があります。例えば、階層型インデックスで行った集計結果を、元の列として扱いたい場合などです。</p>
<p>このような場合は、<code>reset_index()</code> メソッドを使用します。このメソッドを呼び出すと、階層型インデックスの各レベルが通常の列として DataFrame に追加され、デフォルトの整数インデックスが新たに設定されます。</p>
<p><code>reset_index()</code> は新しい DataFrame を返すため、元の DataFrame を変更したい場合は、結果を同じ変数に代入するか、<code>inplace=True</code> 引数を指定します（ただし、<code>inplace=True</code> の使用は推奨されない場合があります）。</p>
<p>ここでは、<code>sales_hier_df</code> に設定した pandas MultiIndex をリセットし、&#8217;月&#8217;と&#8217;店舗&#8217;を再び列に戻してみましょう。元の <code>sales_df</code> と同じ形式に戻ることが分かります。</p>
<pre class="language-python" data-prismjs-copy><code class="language-python">
print('リセット前')
display(sales_hier_df)

print('インデックスをリセット後')
sales_reset_df = sales_hier_df.reset_index()
display(sales_reset_df)
</code></pre>
<pre>リセット前
</pre>

  <div id="df-893f24df-dc20-4095-871d-d41e9cf9354f" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th></th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
    <tr>
      <th>月</th>
      <th>店舗</th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th rowspan="3" valign="top">2023-01</th>
      <th>A</th>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>B</th>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-02</th>
      <th>B</th>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>A</th>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th rowspan="3" valign="top">2023-03</th>
      <th>B</th>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>B</th>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>A</th>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-893f24df-dc20-4095-871d-d41e9cf9354f')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-893f24df-dc20-4095-871d-d41e9cf9354f button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-893f24df-dc20-4095-871d-d41e9cf9354f');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-eac81b99-0a06-439d-a4ce-7da57311eb76">
      <button class="colab-df-quickchart" onclick="quickchart('df-eac81b99-0a06-439d-a4ce-7da57311eb76')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-eac81b99-0a06-439d-a4ce-7da57311eb76 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_8a8f65ba-d2ea-4455-b806-a9afae3f3b6a">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_hier_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_8a8f65ba-d2ea-4455-b806-a9afae3f3b6a button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_hier_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<pre>インデックスをリセット後
</pre>

  <div id="df-ed3ef606-76e6-4640-ac92-c83513da0105" class="colab-df-container">
    <div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>月</th>
      <th>店舗</th>
      <th>商品</th>
      <th>売上（円）</th>
      <th>売上原価（円）</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>2023-01</td>
      <td>A</td>
      <td>りんご</td>
      <td>1000</td>
      <td>700</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2023-01</td>
      <td>A</td>
      <td>バナナ</td>
      <td>800</td>
      <td>500</td>
    </tr>
    <tr>
      <th>2</th>
      <td>2023-01</td>
      <td>B</td>
      <td>りんご</td>
      <td>1200</td>
      <td>700</td>
    </tr>
    <tr>
      <th>3</th>
      <td>2023-02</td>
      <td>B</td>
      <td>バナナ</td>
      <td>900</td>
      <td>600</td>
    </tr>
    <tr>
      <th>4</th>
      <td>2023-02</td>
      <td>A</td>
      <td>りんご</td>
      <td>1100</td>
      <td>700</td>
    </tr>
    <tr>
      <th>5</th>
      <td>2023-02</td>
      <td>A</td>
      <td>バナナ</td>
      <td>850</td>
      <td>400</td>
    </tr>
    <tr>
      <th>6</th>
      <td>2023-03</td>
      <td>B</td>
      <td>りんご</td>
      <td>1300</td>
      <td>700</td>
    </tr>
    <tr>
      <th>7</th>
      <td>2023-03</td>
      <td>B</td>
      <td>バナナ</td>
      <td>950</td>
      <td>550</td>
    </tr>
    <tr>
      <th>8</th>
      <td>2023-03</td>
      <td>A</td>
      <td>バナナ</td>
      <td>850</td>
      <td>500</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-ed3ef606-76e6-4640-ac92-c83513da0105')"
            title="Convert this dataframe to an interactive table."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960">
    <path d="M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z"/>
  </svg>
    </button>

  <style>
    .colab-df-container {
      display:flex;
      gap: 12px;
    }

    .colab-df-convert {
      background-color: #E8F0FE;
      border: none;
      border-radius: 50%;
      cursor: pointer;
      display: none;
      fill: #1967D2;
      height: 32px;
      padding: 0 0 0 0;
      width: 32px;
    }

    .colab-df-convert:hover {
      background-color: #E2EBFA;
      box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
      fill: #174EA6;
    }

    .colab-df-buttons div {
      margin-bottom: 4px;
    }

    [theme=dark] .colab-df-convert {
      background-color: #3B4455;
      fill: #D2E3FC;
    }

    [theme=dark] .colab-df-convert:hover {
      background-color: #434B5C;
      box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
      filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
      fill: #FFFFFF;
    }
  </style>

    <script>
      const buttonEl =
        document.querySelector('#df-ed3ef606-76e6-4640-ac92-c83513da0105 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-ed3ef606-76e6-4640-ac92-c83513da0105');
        const dataTable =
          await google.colab.kernel.invokeFunction('convertToInteractive',
                                                    [key], {});
        if (!dataTable) return;

        const docLinkHtml = 'Like what you see? Visit the ' +
          '<a target="_blank" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'
          + ' to learn more about interactive tables.';
        element.innerHTML = '';
        dataTable['output_type'] = 'display_data';
        await google.colab.output.renderOutput(dataTable, element);
        const docLink = document.createElement('div');
        docLink.innerHTML = docLinkHtml;
        element.appendChild(docLink);
      }
    </script>
  </div>


    <div id="df-214258f7-d48c-405c-bb11-d0f467b805e6">
      <button class="colab-df-quickchart" onclick="quickchart('df-214258f7-d48c-405c-bb11-d0f467b805e6')"
                title="Suggest charts"
                style="display:none;">

<svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
     width="24px">
    <g>
        <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </g>
</svg>
      </button>

<style>
  .colab-df-quickchart {
      --bg-color: #E8F0FE;
      --fill-color: #1967D2;
      --hover-bg-color: #E2EBFA;
      --hover-fill-color: #174EA6;
      --disabled-fill-color: #AAA;
      --disabled-bg-color: #DDD;
  }

  [theme=dark] .colab-df-quickchart {
      --bg-color: #3B4455;
      --fill-color: #D2E3FC;
      --hover-bg-color: #434B5C;
      --hover-fill-color: #FFFFFF;
      --disabled-bg-color: #3B4455;
      --disabled-fill-color: #666;
  }

  .colab-df-quickchart {
    background-color: var(--bg-color);
    border: none;
    border-radius: 50%;
    cursor: pointer;
    display: none;
    fill: var(--fill-color);
    height: 32px;
    padding: 0;
    width: 32px;
  }

  .colab-df-quickchart:hover {
    background-color: var(--hover-bg-color);
    box-shadow: 0 1px 2px rgba(60, 64, 67, 0.3), 0 1px 3px 1px rgba(60, 64, 67, 0.15);
    fill: var(--button-hover-fill-color);
  }

  .colab-df-quickchart-complete:disabled,
  .colab-df-quickchart-complete:disabled:hover {
    background-color: var(--disabled-bg-color);
    fill: var(--disabled-fill-color);
    box-shadow: none;
  }

  .colab-df-spinner {
    border: 2px solid var(--fill-color);
    border-color: transparent;
    border-bottom-color: var(--fill-color);
    animation:
      spin 1s steps(1) infinite;
  }

  @keyframes spin {
    0% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
      border-left-color: var(--fill-color);
    }
    20% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    30% {
      border-color: transparent;
      border-left-color: var(--fill-color);
      border-top-color: var(--fill-color);
      border-right-color: var(--fill-color);
    }
    40% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-top-color: var(--fill-color);
    }
    60% {
      border-color: transparent;
      border-right-color: var(--fill-color);
    }
    80% {
      border-color: transparent;
      border-right-color: var(--fill-color);
      border-bottom-color: var(--fill-color);
    }
    90% {
      border-color: transparent;
      border-bottom-color: var(--fill-color);
    }
  }
</style>

      <script>
        async function quickchart(key) {
          const quickchartButtonEl =
            document.querySelector('#' + key + ' button');
          quickchartButtonEl.disabled = true;  // To prevent multiple clicks.
          quickchartButtonEl.classList.add('colab-df-spinner');
          try {
            const charts = await google.colab.kernel.invokeFunction(
                'suggestCharts', [key], {});
          } catch (error) {
            console.error('Error during call to suggestCharts:', error);
          }
          quickchartButtonEl.classList.remove('colab-df-spinner');
          quickchartButtonEl.classList.add('colab-df-quickchart-complete');
        }
        (() => {
          let quickchartButtonEl =
            document.querySelector('#df-214258f7-d48c-405c-bb11-d0f467b805e6 button');
          quickchartButtonEl.style.display =
            google.colab.kernel.accessAllowed ? 'block' : 'none';
        })();
      </script>
    </div>

  <div id="id_0b2be048-2812-45b6-a7e9-c279221213ea">
    <style>
      .colab-df-generate {
        background-color: #E8F0FE;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: none;
        fill: #1967D2;
        height: 32px;
        padding: 0 0 0 0;
        width: 32px;
      }

      .colab-df-generate:hover {
        background-color: #E2EBFA;
        box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);
        fill: #174EA6;
      }

      [theme=dark] .colab-df-generate {
        background-color: #3B4455;
        fill: #D2E3FC;
      }

      [theme=dark] .colab-df-generate:hover {
        background-color: #434B5C;
        box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);
        filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));
        fill: #FFFFFF;
      }
    </style>
    <button class="colab-df-generate" onclick="generateWithVariable('sales_reset_df')"
            title="Generate code using this dataframe."
            style="display:none;">

  <svg xmlns="http://www.w3.org/2000/svg" height="24px"viewBox="0 0 24 24"
       width="24px">
    <path d="M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z"/>
  </svg>
    </button>
    <script>
      (() => {
      const buttonEl =
        document.querySelector('#id_0b2be048-2812-45b6-a7e9-c279221213ea button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      buttonEl.onclick = () => {
        google.colab.notebook.generateWithVariable('sales_reset_df');
      }
      })();
    </script>
  </div>

    </div>
  </div>

<h2><span id="toc23">まとめ: Pandas MultiIndex を使いこなしてデータ分析を効率化</span></h2>
<p>この 記事 では、pandas の階層型インデックス（pandas MultiIndex）の基本的な使い方から、データの絞り込み、インデックスレベルを活かした集計方法までを、実際のデータとコードで具体的に学びました。</p>
<p><strong>pandas MultiIndex を効果的に使うことで、複数のカテゴリを持つ複雑なデータも整理しやすくなり、特定の条件でのデータ抽出や、各階層ごとの集計が効率的に行えるようになります。</strong> 例えば、「特定の月と店舗の売上を知りたい」「月ごとの売上合計を把握したい」といった具体的な分析ニーズに対し、pandas MultiIndex は強力な解決策を提供します。これにより、より深いデータ分析が可能になります。</p>
<p><strong>学んだこと:</strong></p>
<p>&#8211; <code>set_index()</code> による pandas MultiIndex の作成</p>
<p>&#8211; pandas MultiIndex を持つ DataFrame から、<code>[]</code> や <code>.loc</code> を使った列の選択</p>
<p>&#8211; 位置による行の絞り込み（<code>.iloc</code>についても触れました）</p>
<p>&#8211; <code>.loc</code> を使ったインデックスラベルによる行の絞り込み（単一・複数レベル、<code>slice(None)</code>の活用）</p>
<p>&#8211; <code>.loc</code> 使用時の <code>PerformanceWarning</code> の原因と、<code>sort_index()</code> によるパフォーマンス改善策</p>
<p>&#8211; <code>groupby(level=...)</code> を使った様々な pandas MultiIndex レベルでの集計（店舗別、月別、月・店舗別）</p>
<p>&#8211; <code>drop()</code> を使ったインデックス要素の削除</p>
<p>&#8211; <code>reset_index()</code> を使って pandas MultiIndex を通常の列に戻す方法</p>
<p>ぜひ、あなたのデータでも pandas MultiIndex を活用して、データ分析を効率化してみてください。この Notebook で紹介した様々なテクニックが、日々のデータ操作や分析の強力な味方となるはずです。</p>
<h3><span id="toc24">次のステップ</span></h3>
<ul>
<li>今回使用したサンプルデータを変更して、色々な絞り込みや集計を試してみましょう。</li>
<li>あなたの持っている実際のデータに pandas MultiIndex を適用して、どのように分析が効率化されるか体験してみましょう。</li>
<li><code>groupby()</code> の他の集計関数（<code>.mean()</code>, <code>.count()</code>, <code>.max()</code>, <code>.min()</code>など）を使って、様々な観点からデータを分析してみましょう。</li>
</ul>


</body>
</html>



<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc25">関連記事</span></h3> <ul> 
<ul>
  <li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li> </ul> </div>
<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ -->



<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->


<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1760196168623" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">MultiIndexとは何ですか？</span></h3>
<div class="rank-math-answer ">

<p>pandasの階層型インデックス機能で、行や列に複数の階層を持たせることができます。</p>

</div>
</div>
<div id="faq-question-1760196192601" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">MultiIndexを作成する方法は？</span></h3>
<div class="rank-math-answer ">

<p><code>pd.MultiIndex.from_tuples()</code> や <code>set_index()</code> で階層を定義できます。</p>

</div>
</div>
<div id="faq-question-1760196206939" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">stack/unstackの役割は？</span></h3>
<div class="rank-math-answer ">

<p>行と列の階層を入れ替える操作で、MultiIndexを利用した集計に便利です。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-multiindex/">pandas MultiIndex完全ガイド｜階層型インデックスの作成・選択・集計方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-multiindex/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</title>
		<link>https://pythondatalab.com/pandas-groupby-agg/</link>
					<comments>https://pythondatalab.com/pandas-groupby-agg/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sun, 29 Jun 2025 06:30:17 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=925</guid>

					<description><![CDATA[<p>groupbyは「グループごとに集計する」ための基本機能です。 このページではgroupbyの基本から、aggでの集計、filterの使い方まで例で解説します。 💡 Pandas DataFrame入門シリーズ このペー [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
groupbyは「グループごとに集計する」ための基本機能です。
このページではgroupbyの基本から、aggでの集計、filterの使い方まで例で解説します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.css" />
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
<style>
pre[class*="language-"] {
  margin: 0 !important;
  padding: 1em;
}
</style>
</head>
<body>
<script>Prism.highlightAll();</script>

<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->
<p><strong>ビジネスデータ分析の鍵：Pandas <code>groupby()</code> と集計でデータから価値を引き出す！</strong></p>

<p>ビジネスの現場では、膨大なデータの中から意味のある情報を見つけ出し、意思決定に活かすことが不可欠です。「合計売上は？」「どの顧客層が最も貢献しているか？」「ウェブサイトのどのページがよく見られているか？」&#8230; これらの問いに答えるためには、「特定のグループごとにデータをまとめる」という集計作業が欠かせません。</p>

<p>Pandas の強力な <code>groupby()</code> 機能を使えば、このような複雑な集計も Python コードで簡単かつ柔軟に行うことができます。カテゴリ別売上、ユーザー別アクセスなど、具体的なビジネスデータの例を通して、Pandas を使ったデータ集計・分析の基本から応用までを分かりやすく解説します。</p>

<p>この記事を読むことで、以下のことができるようになります：</p>

<ul>
<li>Pandas の <code>groupby()</code> を使ってデータを効率的にグループ化する。</li>
<li><code>sum()</code>, <code>mean()</code>, <code>count()</code>, <code>nunique()</code> といった基本的な集計を適用する。</li>
<li><code>agg()</code> を使って、カラムごとに異なる、あるいは複数の集計を一度に行う。</li>
<li>実務データを集計・分析し、そこからビジネス的な洞察を得る。</li>
</ul>

<p>▶️ 公式ドキュメントも参考にしてください：</p>

<ul>
<li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" target="_blank">pandas DataFrame.groupby Documentation</a></li>
<li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.agg.html" target="_blank">pandas GroupBy.agg Documentation</a></li>
<li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mean.html" target="_blank">pandas DataFrame.mean Documentation</a></li>
<li><a rel="noopener" href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.sum.html" target="_blank">pandas DataFrame.sum Documentation</a></li>
</ul>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-9" checked><label class="toc-title" for="toc-checkbox-9">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">サンプルデータの作成</a></li><li><a href="#toc2" tabindex="0">📌 基本：groupby()によるデータのグループ化</a></li><li><a href="#toc3" tabindex="0">📊 単一集計：sum() / mean() / count() / nunique()</a></li><li><a href="#toc4" tabindex="0">🔧 応用：agg()で複数集計を一度に</a></li><li><a href="#toc5" tabindex="0">実務例①：カテゴリ別売上データの分析</a><ol><li><a href="#toc6" tabindex="0">分析結果：カテゴリ別売上合計</a></li><li><a href="#toc7" tabindex="0">分析結果：カテゴリ別商品の多様性と価格帯</a></li><li><a href="#toc8" tabindex="0">実務例①のまとめ</a></li></ol></li><li><a href="#toc9" tabindex="0">実務例②：ユーザー別アクセスデータの分析</a><ol><li><a href="#toc10" tabindex="0">分析結果：ユーザー別アクセスデータ</a></li><li><a href="#toc11" tabindex="0">実務例②のまとめ</a></li></ol></li><li><a href="#toc12" tabindex="0">まとめ</a><ol><li><a href="#toc13" tabindex="0">関連記事</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">サンプルデータの作成</span></h2>

<p>まずは「カテゴリ別売上集計」の例として、架空の売上データを作成します。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
import pandas as pd

# サンプル売上データ
data = {
    'category': ['A', 'B', 'A', 'C', 'B', 'A', 'C', 'B'],
    'item':     ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'apple', 'banana'],
    'price':    [100, 200, 150, 120, 180, 210, 130, 190],
    'quantity': [2, 1, 3, 1, 2, 1, 2, 1]
}
df_sales = pd.DataFrame(data)
print("元の売上データ：")
display(df_sales)
</code>
</pre>

<p>元の売上データ:</p>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">item</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">orange</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">150</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">orange</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">180</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">210</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">130</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table>
<h2><span id="toc2">📌 基本：groupby()によるデータのグループ化</span></h2>

<p>このセクションでは、データ集計の第一歩となる <code>groupby()</code> メソッドの基本的な使い方を学びます。<code>groupby()</code> は、指定した一つ以上の列の値に基づいてデータをグループに分割する機能です。このグループ化されたオブジェクトに対して、後続の集計処理を適用します。</p>

<p>データフレームをグループ化することで、各グループに対して個別に集計処理を適用する準備が整います。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# category列でグループ化
grouped = df_sales.groupby('category')
print(grouped)
</code>
</pre>
<p>この状態ではまだ集計は行われていません。続いて集計メソッドを適用します。</p>

<h2><span id="toc3">📊 単一集計：sum() / mean() / count() / nunique()</span></h2>

<p><code>groupby()</code>でデータをグループ化した後、各グループに対して集計処理を行います。Pandasでは、よく使う「合計」「平均」「カウント」「ユニーク数のカウント」といった単一の集計は、専用のショートカットメソッドで簡単に計算可能です。</p>

<ul>
<li><code>sum()</code>: グループ内の合計値を計算します。</li>
<li><code>mean()</code>: グループ内の平均値を計算します。</li>
<li><code>count()</code>: グループ内の非欠損値の数をカウントします。</li>
<li><code>nunique()</code>: グループ内のユニークな要素の数をカウントします。</li>
</ul>

<p>これらのメソッドを使うことで、各グループの基本的な要約統計量を素早く把握できます。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# sum
sales_sum = grouped[['price', 'quantity']].sum()
print("カテゴリ別 合計値：")
display(sales_sum)

# mean
sales_mean = grouped[['price', 'quantity']].mean()
print("カテゴリ別 平均値：")
display(sales_mean)

# count
print("カテゴリ別 項目数 (count)：")
display(grouped.count())

# nunique
print("カテゴリ別 ユニークアイテム数 (nunique)：")
display(grouped['item'].nunique())

print("カテゴリ別 ユニークな価格数 (nunique)：")
display(grouped['price'].nunique())
</code>
</pre>

<p>カテゴリ別　合計値:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">460</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">570</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">250</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
</tbody>
</table>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>

<p>カテゴリ別　平均値:</p>


<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">153.333333</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2.000000</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1.333333</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">125.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1.500000</td>
</tr>
</tbody>
</table>

<p>カテゴリ別　項目数（count）:</p>


<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">item</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>

<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
</tbody>
</table>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">item</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>

<p>カテゴリ別　ユニークアイテム数(nunique）:</p>

<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table>


<p>カテゴリ別　ユニークな価格数(nunique）:</p>


<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
</tbody>
</table>
<p>（⚠️注意）
グループ化されたデータフレームに対して grouped.sum() や grouped.mean() のような集計関数を適用する際、文字列型のデータが含まれているとエラーが発生することがあります。例えば、grouped.mean()は数値データにのみ有効であるため、数値データである price や quantity の列を指定して、grouped[[&#8216;price&#8217;, &#8216;quantity&#8217;]]を実行します。なお、複数列を扱うため、[[ ]]にする必要があります。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# 下記の平均を実行すると、item列が文字列データのためエラーが出ます。
sales_mean = grouped.mean()
print("カテゴリ別 平均値：")
display(sales_mean)
</code>
</pre>
<h2><span id="toc4">🔧 応用：agg()で複数集計を一度に</span></h2>

<p><code>agg()</code> メソッドは、<code>groupby()</code> と組み合わせて使うことで、より柔軟な集計を可能にします。<code>agg()</code>を使うと、カラムごとに異なる集計関数を一度に適用したり、同じカラムに対して複数の集計関数を適用したりできます。これは、データフレーム全体の要約統計量を一度に計算したい場合に非常に便利です。Pandas に組み込まれている集計関数だけでなく、NumPy の関数や、独自のカスタム関数を使うことも可能です。</p>

<p><code>agg()</code> を使いこなすことで、複雑な集計ニーズにも柔軟に対応できるようになります。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# 複数集計例1：quantityの合計、priceの平均・最大・最小
result1 = grouped.agg({
    'quantity': 'sum',
    'price':    ['mean', 'max', 'min']
})

print("カテゴリ別 複数集計1：")
display(result1)


</code>
</pre>
<p>カテゴリ別　複数集計1:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
<th colspan="3" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">sum</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">mean</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">max</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">min</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">153.333333</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">210</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">100</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">180</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">125.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">130</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120</td>
</tr>
</tbody>
</table>
<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# 複数集計2: quantityの合計と平均、priceの平均と中央値
result2 = grouped.agg({
    'quantity': ['sum', 'mean'],
    'price':    ['mean', 'median']
})

print("カテゴリ別 複数集計2：")
display(result2)
</code>
</pre>

<p>カテゴリ別　複数集計2:</p>

<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
<th colspan="2" halign="left" style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">sum</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">mean</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">mean</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">median</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">153.333333</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">150.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1.333333</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190.0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1.500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">125.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">125.0</td>
</tr>
</tbody>
</table>
<h2><span id="toc5">実務例①：カテゴリ別売上データの分析</span></h2>

<p>ここでは、架空の売上データを使って、カテゴリ別の売上金額や商品の多様性について分析を行います。ビジネスの現場で最も頻繁に行われる分析の一つです。</p>

<p>分析のポイント：
*   <strong>売上金額</strong> = price × quantity を計算する。
*   カテゴリ別に売上金額の合計を集計する。
*   カテゴリ別に商品の種類（ユニーク項目数）や価格帯の多様性（ユニーク価格数）を集計する。
*   これらの集計結果から、各カテゴリの特徴や改善点を探る。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# 売上金額列（revenue）を追加
df_sales['revenue'] = df_sales['price'] * df_sales['quantity']
print("売上金額列追加：")
display(df_sales)

# revenueの合計をカテゴリ別に集計
cat_rev = df_sales.groupby('category')['revenue'].sum()
print("カテゴリ別 売上合計：")
display(cat_rev)

# category列を通常の列に戻す
cat_rev = cat_rev.reset_index()
print("カテゴリ別 売上合計：")
display(cat_rev)
</code>
</pre>
<p>売上金額列追加:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">item</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">price</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">quantity</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">revenue</th>
</tr>
</thead>



<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">orange</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">150</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">450</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">orange</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">180</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">360</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">210</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">210</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">apple</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">130</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">260</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">banana</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">190</td>
</tr>
</tbody>
</table>

<p>カテゴリ別　売上合計:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">revenue</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">A</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">860</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">B</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">750</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">C</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">380</td>
</tr>
</tbody>
</table>
<p>カテゴリ別　売上合計:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">category</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">revenue</th>
</tr>
</thead>


<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">860</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">750</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">380</td>
</tr>
</tbody>
</table>
<h3><span id="toc6">分析結果：カテゴリ別売上合計</span></h3>

<p>カテゴリ別の売上合計を見てみると、カテゴリ A が最も売上が高く 860 円、次いでカテゴリ B が 750 円、カテゴリ C が 380 円となっています（下図参照）。これは、カテゴリ A と B がより多くの商品を提供しているか、あるいは高価な商品を扱っている可能性を示唆しています。カテゴリ C は他のカテゴリに比べて売上が低い傾向にあることが分かります。</p>

<p></p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
!pip install japanize-matplotlib # Google Colabなどで簡単に日本語表示を可能にするライブラリ
import japanize_matplotlib


# カテゴリ別売上合計を棒グラフで可視化
plt.figure(figsize=(8, 5))
plt.bar(cat_rev['category'], cat_rev['revenue'], color=['skyblue', 'lightcoral', 'lightgreen'])
plt.title('カテゴリ別 売上合計')
plt.xlabel('カテゴリ')
plt.ylabel('売上合計 (円)')
plt.grid(axis='y', linestyle='--')
plt.show()
</code>
</pre>

<!-- カテゴリ別売上合計 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/06/Total-Sales-by-Category.png" 
       alt="カテゴリ別売上合計を棒グラフで可視化。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：カテゴリ別売上合計</figcaption>
</figure>


<h3><span id="toc7">分析結果：カテゴリ別商品の多様性と価格帯</span></h3>

<p>次に、カテゴリごとの商品の多様性（ユニーク項目数）と価格帯の多様性（ユニーク価格数）を見てみましょう。</p>

<p>カテゴリ別のユニーク項目数とユニーク価格数を見ると、カテゴリ A はユニーク項目数が 3 つ、ユニーク価格数が 3 つとなっており、比較的多くの種類の商品を、多様な価格帯で扱っていることが分かります（下図参照）。カテゴリ B はユニーク項目数が 2 つ、ユニーク価格数が 3 つとなっており、カテゴリ A と同様に多様な価格帯で商品を扱っていますが、項目数はやや少ないです。一方、カテゴリ C はユニーク項目数が 1 つ、ユニーク価格数が 2 つとなっており、提供している商品の種類が少なく、価格帯も限定的であることが示唆されます。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
import matplotlib.pyplot as plt
import pandas as pd

# サンプル売上データ (df_salesの再作成)
data = {
    'category': ['A', 'B', 'A', 'C', 'B', 'A', 'C', 'B'],
    'item':     ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'apple', 'banana'],
    'price':    [100, 200, 150, 120, 180, 210, 130, 190],
    'quantity': [2, 1, 3, 1, 2, 1, 2, 1]
}
df_sales = pd.DataFrame(data)


# カテゴリ別ユニーク項目数と価格数を再度計算
grouped = df_sales.groupby('category')
unique_item_counts = grouped['item'].nunique()
unique_price_counts = grouped['price'].nunique()


# カテゴリ別ユニーク項目数と価格数を可視化
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# ユニーク項目数
axes[0].bar(unique_item_counts.index, unique_item_counts.values, color='teal')
axes[0].set_title('カテゴリ別 ユニーク項目数')
axes[0].set_xlabel('カテゴリ')
axes[0].set_ylabel('ユニーク項目数')
axes[0].grid(axis='y', linestyle='--')

# ユニーク価格数
axes[1].bar(unique_price_counts.index, unique_price_counts.values, color='purple')
axes[1].set_title('カテゴリ別 ユニーク価格数')
axes[1].set_xlabel('カテゴリ')
axes[1].set_ylabel('ユニーク価格数')
axes[1].grid(axis='y', linestyle='--')

plt.tight_layout()
plt.show()
</code>
</pre>

<!-- カテゴリ別ユニーク項目数、価格数 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/06/Unique-Item-Count-by-Category_Unique-Price-Count-by-Category.png" 
       alt="カテゴリ別ユニーク項目数、価格数を棒グラフで可視化。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：カテゴリ別ユニーク項目数・価格数</figcaption>
</figure>


<h3><span id="toc8">実務例①のまとめ</span></h3>

<p>カテゴリ別の売上、商品の種類、価格帯の分析から、各カテゴリの強みや課題が見えてきました。カテゴリ A と B は多様な商品を扱っており売上も高い一方、カテゴリ C は売上が低く、商品ラインナップや価格戦略の見直しが必要かもしれません。</p>

<h2><span id="toc9">実務例②：ユーザー別アクセスデータの分析</span></h2>

<p>次に、ウェブサイトのアクセスログデータを使って、ユーザーごとの行動を分析する例を見てみましょう。ユーザーのアクセス回数、ユニークな閲覧ページ数、サイト滞在時間などを集計することで、ユーザーのエンゲージメントやサイトへの関心度を測ることができます。</p>

<p>分析のポイント：
*   ユーザーごとにアクセス回数をカウントする。
*   各ユーザーがアクセスしたユニークなページ数をカウントする。
*   ユーザーごとのサイト滞在時間（セッション時間）を計算する（簡易版）。
*   これらの集計結果から、ユーザーの行動パターンやエンゲージメントレベルを把握する。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# サンプルアクセスログ
data2 = {
  'user_id':   [101, 102, 101, 103, 102, 101],
  'page':      ['A','B','A','A','C','B'],
  'timestamp': pd.date_range('2025-01-01', periods=6, freq='H')
}

df_log = pd.DataFrame(data2)
print("元のアクセスログ：")
display(df_log)

# ユーザーごとのアクセス回数をカウント
access_count = df_log.groupby('user_id').size().reset_index(name='count')
print("ユーザー別 アクセス回数：")
display(access_count)

# 各ユーザーがアクセスしたユニークなページ数をカウント
unique_pages_per_user = df_log.groupby('user_id')['page'].nunique()
print("ユーザー別 ユニークなページ数：")
display(unique_pages_per_user)

</code>
</pre>

<p>元のアクセスログ:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">user_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">page</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">timestamp</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">101</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 00:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 01:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">101</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 02:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 03:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 04:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">101</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 05:00:00</td>
</tr>
</tbody>
</table>

<p>ユーザー別　アクセス回数:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">user_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">count</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">101</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table>
<p>ユーザー別　ユニークなページ数:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">page</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">user_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">101</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">102</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">103</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table>

<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>コード解説</title>
    <style>
        #explanation {
            display: none; /* 初期状態では非表示 */
            border: 1px solid #ccc;
            padding: 15px;
            margin-top: 20px;
            background-color: #f9f9f9;
        }
        .toggle-link {
            color: blue;
            cursor: pointer;
            text-decoration: underline;
        }
    </style>
</head>
<body>

    <p><span class="toggle-link" onclick="toggleExplanation()">コードの解説</span></p>

    <div id="explanation">
        <p>コードの解説</p>
        <ol>
            <li>サンプルアクセスログデータの作成:</li>
        </ol>
        <ul>
            <li>data2 = { &#8230; }: ユーザー ID、アクセスしたページ、タイムスタンプを含む辞書を作成しています。これがアクセスログの元データとなります。</li>
            <li>&#8216;timestamp&#8217;: pd.date_range(&#8216;2025-01-01&#8242;, periods=6, freq=&#8217;H&#8217;): ここで Pandas の機能を使って、2025 年 1 月 1 日から 1 時間おきに 6 つのタイムスタンプ（日時データ）を自動的に生成しています。`freq=&#8217;H&#8217;`は「1 時間ごと」を意味します。</li>
        </ul>

        <ol start="2">
            <li>Pandas DataFrame の作成:</li>
        </ol>
        <ul>
            <li>df_log = pd.DataFrame(data2): 上記で作成した辞書`data2`を使って、Pandas の DataFrame `df_log` を作成しています。これにより、表形式のデータとして扱いやすくなります。</li>
        </ul>

        <ol start="3">
            <li>元のアクセスログの表示:</li>
        </ol>
        <ul>
            <li>print(&#8220;元のアクセスログ：&#8221;): 見出しを表示します。</li>
            <li>display(df_log): 作成した DataFrame `df_log` の内容を表示します。</li>
        </ul>

        <ol start="4">
            <li>ユーザーごとのアクセス回数のカウント:</li>
        </ol>
        <ul>
            <li>df_log.groupby(&#8216;user_id&#8217;): DataFrame を &#8216;user_id&#8217; 列の値でグループ化します。これにより、同じユーザー ID を持つ行がまとめて扱えるようになります。</li>
            <li>.size(): グループ化された各グループ（各ユーザー）に含まれる行数、つまりそのユーザーのアクセス回数をカウントします。</li>
            <li>.reset_index(name=&#8217;count&#8217;): `size()`の結果はデフォルトでは Series 形式で、ユーザー ID がインデックスになっています。これを DataFrame に変換し、カウント数の列に &#8216;count&#8217; という名前を付けています。</li>
            <li>access_count = &#8230;: 結果を `access_count` という新しい DataFrame に格納しています。</li>
            <li>print(&#8220;ユーザー別 アクセス回数：&#8221;): 見出しを表示します。</li>
            <li>display(access_count): ユーザー別アクセス回数が格納された DataFrame `access_count` を表示します。</li>
        </ul>

        <ol start="5">
            <li>各ユーザーがアクセスしたユニークなページ数のカウント:</li>
        </ol>
        <ul>
            <li>df_log.groupby(&#8216;user_id&#8217;): 再度、DataFrame を &#8216;user_id&#8217; 列でグループ化します。</li>
            <li>[&#8216;page&#8217;]: グループ化された DataFrame から、&#8217;page&#8217; 列を選択しています。</li>
            <li>.nunique(): 各ユーザーグループの &#8216;page&#8217; 列に含まれる値の中で、ユニーク（重複しない）な値の数をカウントします。これにより、各ユーザーが何種類のページを見たかが分かります。</li>
            <li>unique_pages_per_user = &#8230;: 結果を `unique_pages_per_user` という Series に格納しています。</li>
            <li>print(&#8220;ユーザー別 ユニークなページ数：&#8221;): 見出しを表示します。</li>
            <li>display(unique_pages_per_user): ユーザー別ユニークページ数が格納された Series `unique_pages_per_user` を表示します。</li>
        </ul>
    </div>

    <script>
        function toggleExplanation() {
            var explanationDiv = document.getElementById('explanation');
            if (explanationDiv.style.display === 'none') {
                explanationDiv.style.display = 'block';
            } else {
                explanationDiv.style.display = 'none';
            }
        }
    </script>

</body>
</html>
<p>ユーザー別セッション時間集計</p>

<p>タイムスタンプを使って、ユーザーごとの滞在時間やセッション時間（簡易版）を計算します。（※サンプルデータがシンプルなので簡易的なものになります）</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# 'user_id'でグループ化し、timestampの最大値と最小値を計算
session_times = df_log.groupby('user_id')['timestamp'].agg(['min', 'max'])

# 簡易的なセッション時間を計算 (最大値 - 最小値)
session_times['duration'] = session_times['max'] - session_times['min']

print("ユーザー別 簡易セッション時間：")
display(session_times)
</code>
</pre>
<p>ユーザー別 簡易セッション時間：:</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">min</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">max</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">duration</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">user_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">101</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 00:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 05:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0 days 05:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">102</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 01:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 04:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0 days 03:00:00</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">103</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 03:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-01-01 03:00:00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0 days 00:00:00</td>
</tr>
</tbody>
</table>
<h3><span id="toc10">分析結果：ユーザー別アクセスデータ</span></h3>

<p>ユーザーごとのアクセス回数、ユニークページ数、簡易セッション時間の集計結果から、以下の点が分かります。</p>

<ul>
<li><strong>ユーザー 101:</strong> アクセス回数が最も多く（3 回）、ユニークページ数も 2 つと複数ページを閲覧しています。セッション時間も 5 時間と最も長いです。これは、ユーザー 101 がサイトに対して最も活発で、複数のコンテンツに興味を持っている可能性を示唆しています（下図参照）。</li>
<li><strong>ユーザー 102:</strong> アクセス回数は 2 回、ユニークページ数も 2 つです。セッション時間は 3 時間です。ユーザー 101 ほどではありませんが、複数のページを閲覧しており、一定のエンゲージメントがあると考えられます。</li>
<li><strong>ユーザー 103:</strong> アクセス回数は 1 回、ユニークページ数も 1 つです。セッション時間も 0 時間となっています（アクセスが 1 回のみのため）。これは、ユーザー 103 が特定のページに一度だけアクセスしただけで、現時点ではサイトへの関心が低いか、目的の情報にすぐにたどり着いた可能性が考えられます。</li>
</ul>

<p>これらの結果から、ユーザーの行動パターンに違いがあることが分かりました。アクセス回数が多いユーザーは、より多くのページを閲覧し、サイトに長く滞在する傾向があるようです（下図参照）。</p>

<blockquote>
  <p>ここでいう「エンゲージメント」とは、ユーザーがウェブサイトやサービスにどれだけ積極的に関与しているか、興味を持っているかを示す指標です。アクセス回数が多い、色々なページを見ている、滞在時間が長いといった行動は、エンゲージメントが高いと解釈できます。</p>
</blockquote>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
import matplotlib.pyplot as plt

# ユーザー別アクセス回数を棒グラフで可視化
plt.figure(figsize=(8, 5))
plt.bar(access_count['user_id'].astype(str), access_count['count'], color='teal')
plt.title('ユーザー別 アクセス回数')
plt.xlabel('ユーザーID')
plt.ylabel('アクセス回数')
plt.grid(axis='y', linestyle='--')
plt.show()
</code>
</pre>

<!-- ユーザー別アクセス回数 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/06/User-Access-Count.png" 
       alt="ユーザー別アクセス回数を棒グラフで可視化。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：ユーザー別アクセス回数</figcaption>
</figure>


<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# ユーザー別ユニークページ数を棒グラフで可視化
plt.figure(figsize=(8, 5))
plt.bar(unique_pages_per_user.index.astype(str), unique_pages_per_user.values, color='purple')
plt.title('ユーザー別 ユニークページ数')
plt.xlabel('ユーザーID')
plt.ylabel('ユニークページ数')
plt.grid(axis='y', linestyle='--')
plt.show()
</code>
</pre>

<!-- ユーザー別　ユニークページ数 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/06/Number-of-Unique-Pages-Visited-per-User.png" 
       alt="ユーザー別　ユニークページ数を棒グラフで可視化。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：ユーザー別　ユニークページ数</figcaption>
</figure>

<p></p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# ユーザー別簡易セッション時間を棒グラフで可視化
# durationを時間単位に変換
session_times['duration_hours'] = session_times['duration'].dt.total_seconds() / 3600

plt.figure(figsize=(8, 5))
plt.bar(session_times.index.astype(str), session_times['duration_hours'], color='lightcoral')
plt.title('ユーザー別 簡易セッション時間')
plt.xlabel('ユーザーID')
plt.ylabel('セッション時間 (時間)')
plt.grid(axis='y', linestyle='--')
plt.show()
</code>
</pre>

<!-- ユーザー別 簡易セッション時間 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/06/User-Specific-Session-Duration.png" 
       alt="ユーザー別 簡易セッション時間を棒グラフで可視化。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：ユーザー別 簡易セッション時間</figcaption>
</figure>


<h3><span id="toc11">実務例②のまとめ</span></h3>

<p>ユーザー行動の分析から、ユーザーによってサイトへの関心度や利用方法が異なることが明らかになりました。特にアクセス回数が少なく滞在時間も短いユーザーに対して、サイトへの再訪やエンゲージメントを高めるための施策を検討することが重要です。</p>

<h2><span id="toc12">まとめ</span></h2>

<p>今回は、Pandas の <code>groupby()</code> および <code>agg()</code>, <code>sum()</code>, <code>mean()</code>, <code>count()</code>, <code>nunique()</code> といった集計関数を使ったデータのグループ化と要約について学びました。</p>

<ul>
<li><code>groupby()</code> を使用して、指定したキー列に基づいてデータを効率的にグループ化できることを確認しました。</li>
<li><code>sum()</code>, <code>mean()</code>, <code>count()</code>, <code>nunique()</code> といった基本的な集計関数を使って、各グループの合計、平均、要素数、ユニーク数を簡単に計算できることを学びました。数値データ以外の列に対して集計関数を適用する際には注意が必要であることも確認しました。</li>
<li><code>agg()</code> を使うことで、単一または複数の列に対して、複数の集計関数を一度に適用できる柔軟な集計方法を習得しました。</li>
<li>実務例として、「カテゴリ別売上集計」と「ユーザー別アクセス数集計」を通して、これらの集計方法がビジネスデータの分析にどのように役立つか具体的なイメージを持つことができました。売上金額の計算、ユーザーのアクセス回数やユニークページ数、簡易的なセッション時間の集計と、そこから得られる示唆について考察を行いました。</li>
<li>集計結果を棒グラフで可視化することで、データの傾向やユーザー行動のパターンをより直感的に理解できることを示しました。</li>
</ul>

<p>これらの Pandas の強力な集計機能を使いこなすことで、ビジネスデータの分析やレポート作成が効率的に行えるようになります。</p>
</body>
</html>





<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ -->
<style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style> <div class="related-box"> <h3><span id="toc13">関連記事</span></h3> <ul> 
<ul>
  <li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
  <li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li> </ul> </div>
<!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ -->


<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->

<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>



<p class="wp-block-paragraph"></p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-groupby-agg/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas mergeの使い方｜DataFrame結合（inner, left, outer）の違いと実例</title>
		<link>https://pythondatalab.com/pandas-merge/</link>
					<comments>https://pythondatalab.com/pandas-merge/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sun, 11 May 2025 08:01:54 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=345</guid>

					<description><![CDATA[<p>pandasのmerge関数をわかりやすく解説。inner/left/outer結合の違い、複数キー結合、suffixesでの重複列対策まで実例付きで紹介。 💡 Pandas DataFrame入門シリーズ このページは [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-merge/">pandas mergeの使い方｜DataFrame結合（inner, left, outer）の違いと実例</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
pandasのmerge関数をわかりやすく解説。inner/left/outer結合の違い、複数キー結合、suffixesでの重複列対策まで実例付きで紹介。
<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->
    <p>Pythonのデータ分析ライブラリ「Pandas」には、データフレームを結合するための便利な機能が備わっています。その中でも、`pd.merge`関数は、特定の列をキーとして複数のデータフレームを結合する際に非常に役立ちます。</p>
    <p>この記事では、`pd.merge`関数を使って、2つのデータフレームを結合する様々な方法を分かりやすく解説していきます。 結合方法には、内部結合、左外部結合、右外部結合、完全外部結合の4パターンがあり、それぞれ異なる結果が得られます。具体的な例を見ながら、それぞれの結合方法の特徴を理解していきましょう。</p>

<p>▶️ concatの公式ドキュメントも参考にしてください：<br /><a rel="noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" target="_blank">pandas DataFrame merge Documentation</a></p>

    
  
  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-11" checked><label class="toc-title" for="toc-checkbox-11">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">なぜmergeが必要なのか？</a></li><li><a href="#toc2" tabindex="0">concatとmergeの違いは？</a></li><li><a href="#toc3" tabindex="0">サンプルデータの作成</a><ol><li><a href="#toc4" tabindex="0">データフレーム1：社員の基本情報</a></li><li><a href="#toc5" tabindex="0">データフレーム2：社員の年収、勤務地など</a></li></ol></li><li><a href="#toc6" tabindex="0">データフレームの結合</a><ol><li><a href="#toc7" tabindex="0">内部結合</a></li><li><a href="#toc8" tabindex="0">左外部結合</a></li><li><a href="#toc9" tabindex="0">右外部結合</a></li><li><a href="#toc10" tabindex="0">完全外部結合</a></li></ol></li><li><a href="#toc11" tabindex="0">まとめ</a><ol><li><a href="#toc12" tabindex="0">関連記事</a></li><li><a href="#toc13" tabindex="0">merge()とjoin()の違いは？</a></li><li><a href="#toc14" tabindex="0">内部結合と外部結合の違いは？</a></li><li><a href="#toc15" tabindex="0">同名列の重複を避けるには？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">なぜmergeが必要なのか？</span></h2>
<p>
  現実のデータ分析では、1つの表（データフレーム）だけで完結することは少なく、複数のデータを組み合わせて扱う場面がよくあります。
  たとえば、社員の基本情報と給与情報が別々のデータフレームで管理されている場合、それらを統合して「誰がどこで働き、いくらもらっているのか」といった情報を得る必要があります。
</p>
<p>
  Pandasの<code>merge()</code>関数は、SQLのJOIN操作と同様に、複数のデータフレームをキーに基づいて柔軟に結合できる強力なツールです。
  データを分析・可視化・機械学習などの処理にかける前段階として、「正しく結合する」ことは非常に重要なプロセスなのです。
</p>

<h2><span id="toc2">concatとmergeの違いは？</span></h2>
<p>
  Pandasには複数のデータフレームを結合する手段として、<code>concat()</code>や<code>merge()</code>などがあります。
  どちらもデータを統合する目的で使われますが、使い方や用途が大きく異なります。
</p>
<table>
  <thead>
    <tr><th>関数</th><th>用途</th><th>結合方法</th></tr>
  </thead>
  <tbody>
    <tr>
      <td><code>concat()</code></td>
      <td>単純な縦方向または横方向の連結</td>
      <td>インデックスやカラムの位置を基準に結合</td>
    </tr>
    <tr>
      <td><code>merge()</code></td>
      <td>共通のキーに基づいてマッチして統合</td>
      <td>SQLのJOINと同じような挙動</td>
    </tr>
  </tbody>
</table>
<p>
  今回のように、<strong>2つの表に共通するキー（この例ではName列）を元に情報を統合したい</strong>場合は、<code>merge()</code>の方が適しています。
  一方、<strong>単に行や列を並べたいだけ</strong>なら、<code>concat()</code>がシンプルで便利です。
</p>

  
  
    <h2><span id="toc3">サンプルデータの作成</span></h2>
    <p>まずは、結合に使用する2つのデータフレームを作成します。これらのデータフレームは、それぞれ社員の基本情報と年収、勤務地などの情報を表しています。</p>
    <h3><span id="toc4">データフレーム1：社員の基本情報</span></h3>
    <pre><code>
import pandas as pd

df1 = pd.DataFrame(
    {"Name": ["Taro", "Hanako", "Jiro"],
     "Age": [23, 29, 35],
     "Occupation": ["Engineer", "Designer", "Teacher"],}
)
df1
    </code></pre>
    <table>
        <thead>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Age</th>
                <th>Occupation</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>0</th>
                <td>Taro</td>
                <td>23</td>
                <td>Engineer</td>
            </tr>
            <tr>
                <th>1</th>
                <td>Hanako</td>
                <td>29</td>
                <td>Designer</td>
            </tr>
            <tr>
                <th>2</th>
                <td>Jiro</td>
                <td>35</td>
                <td>Teacher</td>
            </tr>
        </tbody>
    </table>
    <h3><span id="toc5">データフレーム2：社員の年収、勤務地など</span></h3>
    <pre><code>
df2 = pd.DataFrame(
   {"Name":  ["Taro","Jiro"],
    "Annual Income": [4500000,4900000],
    "Location": ["Tokyo","Nagoya"],
    "Years Employed": [2,10],
    "Index_number":[0,2]}
)
df2
    </code></pre>
    <table>
        <thead>
            <tr>
                <th></th>
                <th>Name</th>
                <th>Annual Income</th>
                <th>Location</th>
                <th>Years Employed</th>
                <th>Index_number</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>0</th>
                <td>Taro</td>
                <td>4500000</td>
                <td>Tokyo</td>
                <td>2</td>
                <td>0</td>
            </tr>
            <tr>
                <th>1</th>
                <td>Jiro</td>
                <td>4900000</td>
                <td>Nagoya</td>
                <td>10</td>
                <td>2</td>
            </tr>
        </tbody>
    </table>
    
    <h2><span id="toc6">データフレームの結合</span></h2>
    <p>それでは、作成した2つのデータフレームを`pd.merge`関数を使って結合してみましょう。結合方法は、`how`引数で指定します。</p>
    <h3><span id="toc7">内部結合</span></h3>
    <p>内部結合では、両方のデータフレームに共通するキーを持つ行だけが結合されます。キーとして指定されていない列は、そのまま結合後のデータフレームに引き継がれます。</p>
    <pre><code>
# 'Name'列をキーとして内部結合
df3 = pd.merge(df1, df2, on="Name")
df3
    </code></pre>



    </code></pre>
    <table>
        <thead>
            <tr>
                <th></th>
                <th>Name</th>
<th>Age</th>
<th>Occupation</th>
                <th>Annual Income</th>
                <th>Location</th>
                <th>Years Employed</th>
                <th>Index_number</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>0</th>
                <td>Taro</td>
<td>23</td>
<td>Engineer</td>
                <td>4500000</td>
                <td>Tokyo</td>
                <td>2</td>
                <td>0</td>
            </tr>
            <tr>
                <th>1</th>
                <td>Jiro</td>
<td>35</td>
<td>Teacher</td>
                <td>4900000</td>
                <td>Nagoya</td>
                <td>10</td>
                <td>2</td>
            </tr>
        </tbody>
    </table>


    <p>上記のコードでは、`on=&#8221;Name&#8221;`と指定することで、&#8217;Name&#8217;列をキーとして内部結合を行っています。つまり、&#8217;Name&#8217;列の値が両方のデータフレームに存在する行だけが結合されます。Hanakoさんの情報は、df2に存在しないため、結合後のデータフレームには含まれません。</p>
    

    <h3><span id="toc8">左外部結合</span></h3>
    <p>左外部結合では、左側のデータフレームの全ての行と、右側のデータフレームでキーが一致する行が結合されます。右側のデータフレームにキーが一致する行がない場合は、対応する列にNaNが代入されます。</p>
    <pre><code>
# 左外部結合
pd.merge(df1, df2, how='left', on='Name')
    </code></pre>

    </code></pre>
   <table>
  <thead>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Age</th>
      <th>Occupation</th>
      <th>Annual Income</th>
      <th>Location</th>
      <th>Years Employed</th>
      <th>Index_number</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>Taro</td>
      <td>23</td>
      <td>Engineer</td>
      <td>4500000</td>
      <td>Tokyo</td>
      <td>2</td>
      <td>0</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Hanako</td>
      <td>29</td>
      <td>Designer</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Jiro</td>
      <td>35</td>
      <td>Teacher</td>
      <td>4900000</td>
      <td>Nagoya</td>
      <td>10</td>
      <td>2</td>
    </tr>
  </tbody>
</table>






    <p>上記のコードでは、`how=&#8217;left&#8217;`と指定することで、左外部結合を行っています。df1の全ての行が結果に含まれ、df2にキー(&#8216;Name&#8217;)が一致する行がない場合は、対応する列にNaNが代入されます。Hanakoさんの情報は、df2に存在しないため、年収、勤務地などの情報はNaNになります。</p>

    <h3><span id="toc9">右外部結合</span></h3>
    <p>右外部結合は、左外部結合の逆で、右側のデータフレームの全ての行と、左側のデータフレームでキーが一致する行が結合されます。左側のデータフレームにキーが一致する行がない場合は、対応する列にNaNが代入されます。</p>
    <pre><code>
# 右外部結合
pd.merge(df1, df2, how='right', on='Name')
    </code></pre>

   <table>
        <thead>
            <tr>
                <th></th>
                <th>Name</th>
<th>Age</th>
<th>Occupation</th>
                <th>Annual Income</th>
                <th>Location</th>
                <th>Years Employed</th>
                <th>Index_number</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>0</th>
                <td>Taro</td>
<td>23</td>
<td>Engineer</td>
                <td>4500000</td>
                <td>Tokyo</td>
                <td>2</td>
                <td>0</td>
            </tr>
            <tr>
                <th>1</th>
                <td>Jiro</td>
<td>35</td>
<td>Teacher</td>
                <td>4900000</td>
                <td>Nagoya</td>
                <td>10</td>
                <td>2</td>
            </tr>
        </tbody>
    </table>


    <p>上記のコードでは、`how=&#8217;right&#8217;`と指定することで、右外部結合を行っています。df2の全ての行が結果に含まれ、df1にキー(&#8216;Name&#8217;)が一致する行がない場合は、対応する列にNaNが代入されます。今回は、df1とdf2の&#8217;Name&#8217;列の値が全て一致しているため、左外部結合と同じ結果になります。</p>
   
    <h3><span id="toc10">完全外部結合</span></h3>
    <p>完全外部結合では、両方のデータフレームの全ての行が結合されます。どちらかのデータフレームにキーが一致する行がない場合は、対応する列にNaNが代入されます。</p>
    <pre><code>
# 完全外部結合
pd.merge(df1, df2, how='outer', on='Name')
    </code></pre>

<table>
  <thead>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Age</th>
      <th>Occupation</th>
      <th>Annual Income</th>
      <th>Location</th>
      <th>Years Employed</th>
      <th>Index_number</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>Hanako</td>
      <td>29</td>
      <td>Designer</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
      <td>NaN</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Jiro</td>
      <td>35</td>
      <td>Teacher</td>
      <td>4900000</td>
      <td>Nagoya</td>
      <td>10</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Taro</td>
      <td>23</td>
      <td>Engineer</td>
      <td>4500000</td>
      <td>Tokyo</td>
      <td>2</td>
      <td>0</td>
    </tr>
  </tbody>
</table>





    <p>上記のコードでは、`how=&#8217;outer&#8217;`と指定することで、完全外部結合を行っています。df1とdf2の全ての行が結果に含まれ、どちらかのデータフレームにキー(&#8216;Name&#8217;)が一致する行がない場合は、対応する列にNaNが代入されます。Hanakoさんの情報は、df2に存在しないため、年収、勤務地などの情報はNaNになります。また、df2にのみ存在する情報は、df1側の情報がNaNになります。</p>

  <h2><span id="toc11">まとめ</span></h2>
<ul>
  <li>Pandasの<code>merge()</code>関数は、SQLのJOINに似た仕組みで複数のデータフレームをキーに基づいて結合できます。</li>
  <li>主な結合方法は<code>how</code>引数で指定し、<code>'inner'</code>、<code>'left'</code>、<code>'right'</code>、<code>'outer'</code>の4種類があります。</li>
  <li>内部結合は共通するキーのみを結合、外部結合は片方または両方のデータをすべて保持します。</li>
  <li><code>concat()</code>との違いは、「単純な縦横連結」か「キーに基づくマッチング」かという点にあります。</li>
  <li>結合後にNaNが発生するケースもあるため、必要に応じて<code>fillna()</code>や<code>dropna()</code>での後処理を検討しましょう。</li>
</ul>
<p>この記事を通じて、<strong>merge関数の使い方と、各結合パターンの違い・用途</strong>をしっかり理解できたはずです。実務や学習にぜひ役立ててください！</p>




<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ --></p>
<p><style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style></p>
<div class="related-box">
<h3><span id="toc12">関連記事</span></h3>
<ul>
<li style="list-style-type: none;">
<ul>
<li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
<li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li>
</ul>
</li>
</ul>
</div>
<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ --></p>


<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->
<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1760196632236" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc13">merge()とjoin()の違いは？</span></h3>
<div class="rank-math-answer ">

<p>join()はインデックス結合、merge()は列を指定して結合します。</p>

</div>
</div>
<div id="faq-question-1760196651463" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc14">内部結合と外部結合の違いは？</span></h3>
<div class="rank-math-answer ">

<p>innerは共通データのみ、outerは両方すべてのデータを保持します。</p>

</div>
</div>
<div id="faq-question-1760196670972" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc15">同名列の重複を避けるには？</span></h3>
<div class="rank-math-answer ">

<p><code>suffixes=('_left', '_right')</code> で接尾辞を設定します。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-merge/">pandas mergeの使い方｜DataFrame結合（inner, left, outer）の違いと実例</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-merge/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Pandas concat完全ガイド｜複数CSVからDataFrameを縦横結合する方法</title>
		<link>https://pythondatalab.com/pandas-concat/</link>
					<comments>https://pythondatalab.com/pandas-concat/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 26 Apr 2025 08:26:18 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=991</guid>

					<description><![CDATA[<p>この記事ではPandas concat関数を使い、DataFrameを縦結合（axis=0）・横結合（axis=1）する手順をサンプルコード付きで丁寧に解説。ignore_indexの使い分けやよくあるエラー対処、複数C [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-concat/">Pandas concat完全ガイド｜複数CSVからDataFrameを縦横結合する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[
この記事ではPandas concat関数を使い、DataFrameを縦結合（axis=0）・横結合（axis=1）する手順をサンプルコード付きで丁寧に解説。ignore_indexの使い分けやよくあるエラー対処、複数CSVファイルをまとめる実務シナリオも紹介します。


<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.css" />
<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>
<style>
pre[class*="language-"] {
  margin: 0 !important;
  padding: 1em;
}
</style>
</head>
<body>

<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ -->
<p>「複数の CSV ファイルを一つにまとめたい」「異なるデータセットを横に並べて分析したい」&#8230;
データ分析や前処理において、データフレームの結合は避けて通れない重要な作業です。</p>

<p>Python のデータ分析ライブラリ「Pandas」の<code>concat</code>関数を使った、データフレーム（Pandas における表形式のデータ構造）の縦結合・横結合の方法を、初心者の方にも分かりやすいように実例を交えて丁寧に解説します。</p>

<p>この記事を読むことで、以下のことを習得できます。</p>

<ul>
<li><strong>実務での応用:</strong> 実際のデータ前処理で役立つ、効率的なデータ結合のテクニック(特定のフォルダ内の複数のCSVファイルを一気に結合）を身につけられます。</li>
<li><strong><code>Pandas concat</code>関数の基本的な使い方:</strong> 縦方向（行）と横方向（列）への結合方法を理解できます。</li>
<li><strong>インデックス処理の重要性:</strong> 結合時のインデックス（データフレームの各行を識別するためのラベルや番号）の扱いの違い（維持 vs. 振り直し）を理解し、意図しないデータの重複やずれを防ぐ方法を学べます。</li>
</ul>

<p>Pandas を使ったデータ分析を始めたばかりの方や、データ結合の方法でつまずいた経験のある方に特におすすめの内容です。</p>

<hr />

<p>▶️ Pandas concat の公式ドキュメントも参考にしてください：</p>

<p><a rel="noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" target="_blank">pandas DataFrame sort_index Documentation</a></p>

<p>▶️ 他の結合方法である Pandas merge の記事も参考にしてください。Pandas merge や concat と merge の違いについても解説しています。</p>

<p><a href="https://pythondatalab.com/pandas-merge/">Pandas merge 関数でデータフレームを結合する方法【完全解説】</a></p>

<hr />


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-13" checked><label class="toc-title" for="toc-checkbox-13">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">Pandas concat と Pandas merge、使い分けのポイント</a></li><li><a href="#toc2" tabindex="0">サンプルデータの作成（結合前データ）</a></li><li><a href="#toc3" tabindex="0">縦結合・横結合のイメージ</a></li><li><a href="#toc4" tabindex="0">Pandas concatで縦結合する (axis=0)</a><ol><li><a href="#toc5" tabindex="0">追加データの作成</a></li><li><a href="#toc6" tabindex="0">縦に結合（追加データの「インデックス番号」を維持したまま結合：ignore_index=False）</a></li><li><a href="#toc7" tabindex="0">縦に結合（追加データも含めて「インデックス番号」を振り直して結合：ignore_index=True）</a></li></ol></li><li><a href="#toc8" tabindex="0">Pandas concatで横結合する (axis=1)</a><ol><li><a href="#toc9" tabindex="0">追加データの作成</a></li><li><a href="#toc10" tabindex="0">横に結合</a></li></ol></li><li><a href="#toc11" tabindex="0">筆者の体験談：Pandas concatでやってしまった失敗</a></li><li><a href="#toc12" tabindex="0">Pandas concat 実行時によく発生するエラーとその対処法</a><ol><li><a href="#toc13" tabindex="0">1. 列の不一致による問題</a></li><li><a href="#toc14" tabindex="0">2. インデックスの重複による問題 (axis=0, ignore_index=False の場合)</a></li><li><a href="#toc15" tabindex="0">3. 横結合 (axis=1) 時の行数の不一致</a></li></ol></li><li><a href="#toc16" tabindex="0">実務シナリオ：複数の CSV ファイルをまとめて結合する</a></li><li><a href="#toc17" tabindex="0">まとめ</a><ol><li><a href="#toc18" tabindex="0">関連記事</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">Pandas concat と Pandas merge、使い分けのポイント</span></h2>

<p>Pandas でデータフレームを結合する方法には <code>concat</code> の他に <code>merge</code> もあります。どちらを使うべきか迷うこともあるかもしれません。ここでは、それぞれの関数がどのようなケースに適しているかの判断基準を簡単に解説します。</p>

<p><strong><code>pd.concat</code> が適しているケース:</strong></p>

<ul>
<li><strong>単純な縦結合 (行方向への結合):</strong> 複数のデータフレームを単に上下に結合したい場合。例えば、月ごとの売上データをまとめて年間のデータを作成する場合など。</li>
<li><strong>単純な横結合 (列方向への結合):</strong> 同じインデックスを持つデータフレームを横に並べたい場合。例えば、既存のデータフレームに新しい計算結果の列を追加する場合など。</li>
<li><strong>インデックスをキーとした結合:</strong> インデックスが結合のキーとなる場合。</li>
</ul>

<hr />

<p><strong><code>pd.merge</code> が適しているケース:</strong></p>

<ul>
<li><strong>特定のキー列に基づいた結合:</strong> SQLのJOINのように、一つ以上の共通する列（キー）の値に基づいてデータフレームを結合したい場合。例えば、顧客情報データと購入履歴データを顧客IDをキーとして結合する場合など。</li>
<li><strong>異なるインデックスを持つデータフレームの結合:</strong> インデックスが揃っていないデータフレームを、特定の列を基準に結合したい場合。</li>
<li><strong>多様な結合方法（内部結合、外部結合など）を使いたい:</strong> キーに基づいて、データの欠損をどのように扱うか（どちらかのデータにしかない行を含めるかなど）を細かく制御したい場合。</li>
</ul>

<hr />

<p>簡単に言うと、<strong>「単に積み上げたり横に並べたりするなら <code>concat</code>、特定の関係性（キー）で結びつけるなら <code>merge</code>」</strong> と考えると分かりやすいことが多いです。</p>

<p>より詳細な <code>merge</code> の使い方や <code>concat</code> と <code>merge</code> の違いについては、別途記事で詳しく解説していますので、そちらも合わせてご覧ください。</p>

<hr />

<h2><span id="toc2">サンプルデータの作成（結合前データ）</span></h2>

<p>まずは、結合の元となるサンプルデータを作成しましょう。これは、この記事全体を通して使用する基本的なデータフレームです。</p>

<p>以下のコードで、架空の個人情報を含むデータフレーム <code>df</code> を作成します。このデータフレームを基に、concat による様々な結合方法を試していきます。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
import pandas as pd

df = pd.DataFrame({
    &quot;名前&quot;: [&quot;太郎&quot;, &quot;花子&quot;, &quot;次郎&quot;, &quot;美香&quot;, &quot;健一&quot;, &quot;恵子&quot;, &quot;翔&quot;, &quot;茜&quot;, &quot;隆&quot;, &quot;葵&quot;],
    &quot;年齢&quot;: [23, 29, 35, 42, 18, 33, 27, 24, 31, 30],
    &quot;職業&quot;: [&quot;エンジニア&quot;, &quot;デザイナー&quot;, &quot;教師&quot;, &quot;医師&quot;, &quot;学生&quot;, &quot;看護師&quot;, &quot;プログラマー&quot;, &quot;販売員&quot;, &quot;弁護士&quot;, &quot;研究者&quot;],
    &quot;年収（円）&quot;: [4500000, 5500000, 4900000, 7300000, 0, 4000000, 6000000, 3200000, 8000000, 5800000],
    &quot;居住地&quot;: [&quot;東京&quot;, &quot;大阪&quot;, &quot;名古屋&quot;, &quot;札幌&quot;, &quot;福岡&quot;, &quot;東京&quot;, &quot;神戸&quot;, &quot;仙台&quot;, &quot;横浜&quot;, &quot;千葉&quot;],
    &quot;勤続年数&quot;: [2, 4, 10, 15, 1, 5, 3, 1, 12, 8]
})

print(&quot;出力結果&quot;)
df
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">職業</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年収（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">居住地</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">太郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">23</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">エンジニア</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">花子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">デザイナー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">次郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">教師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4900000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">美香</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">医師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">7300000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">札幌</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">健一</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">恵子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">33</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">看護師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">翔</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">27</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">プログラマー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">神戸</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">茜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">販売員</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3200000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">仙台</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">隆</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">弁護士</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">横浜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">葵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">研究者</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">千葉</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8</td>
</tr>
</tbody>
</table>
<h2><span id="toc3">縦結合・横結合のイメージ</span></h2>

<p><code>pd.concat</code>関数を使うことで、複数のデータフレームを縦方向（行方向）または横方向（列方向）に結合できます。この結合の方向は <code>axis</code> 引数で指定します。</p>

<p>以下の図は、縦結合 (<code>axis=0</code>) と横結合 (<code>axis=1</code>) のイメージを示しています。縦結合ではデータが下に追加され、横結合ではデータが右に追加されることが視覚的に理解できます。</p>

<!-- 縦結合、横結合の画像 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/07/vertical-coupling-horizontal-coupling.png" 
       alt="Pandas concatによる結合を示した図。データの縦結合と横結合をしている様子が視覚化されている。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：Pandas concat 縦結合と横結合のイメージ</figcaption>
</figure>
<hr />

<p>次のセクションから、それぞれの具体的な方法を見ていきましょう。</p>

<h2><span id="toc4">Pandas concatで縦結合する (axis=0)</span></h2>

<p>まずは、データフレームを縦方向（行方向）に結合する方法を見ていきましょう。これは、新しい行を既存のデータフレームに追加するイメージです。<code>pd.concat()</code> 関数のデフォルトの動作であり、<code>axis=0</code> を明示的に指定することもできます。</p>

<p>【例】既存のデータフレーム <code>df</code> に、新しいデータを含む１行のデータフレーム <code>df1</code> を縦（行方向）に結合します。</p>

<h3><span id="toc5">追加データの作成</span></h3>

<p>以下のコードで、既存のデータフレームに追加するための新しい１行データを含むデータフレーム <code>df1</code> を作成します。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
df1 = pd.DataFrame({
    &quot;名前&quot;: [&quot;三郎&quot;],
    &quot;年齢&quot;: [18],
    &quot;職業&quot;: [&quot;学生&quot;],
    &quot;年収（円）&quot;: [0],
    &quot;居住地&quot;: [&quot;東京&quot;],
    &quot;勤続年数&quot;: [0]
})

df1
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">職業</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年収（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">居住地</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">三郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
</tbody>
</table>
<h3><span id="toc6">縦に結合（追加データの「インデックス番号」を維持したまま結合：ignore_index=False）</span></h3>

<p><code>pd.concat()</code> 関数で <code>ignore_index=False</code>（デフォルト設定）の場合、結合元のデータフレームのインデックス（行を識別する番号やラベル）がそのまま引き継がれます。元のデータフレームと追加データの両方にインデックス <code>0</code> が存在するため、結合後もインデックス <code>0</code> が重複していることがわかります。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
df2 = pd.concat([df, df1])
df2
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">職業</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年収（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">居住地</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">太郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">23</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">エンジニア</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">花子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">デザイナー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">次郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">教師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4900000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">美香</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">医師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">7300000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">札幌</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">健一</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">恵子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">33</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">看護師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">翔</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">27</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">プログラマー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">神戸</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">茜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">販売員</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3200000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">仙台</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">隆</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">弁護士</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">横浜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">葵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">研究者</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">千葉</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">三郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
</tbody>
</table>
<h3><span id="toc7">縦に結合（追加データも含めて「インデックス番号」を振り直して結合：ignore_index=True）</span></h3>

<p><code>pd.concat()</code> 関数で <code>ignore_index=True</code> を指定すると、結合元のデータフレームのインデックスは無視され、結合された新しいデータフレーム全体に対してゼロから始まる連番のインデックスが自動的に割り当てられます。これにより、インデックスの重複を防ぎ、すっきりとしたデータフレームになります。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
df3 = pd.concat([df, df1], ignore_index=True)
df3
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">職業</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年収（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">居住地</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">太郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">23</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">エンジニア</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">花子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">デザイナー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">次郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">教師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4900000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">美香</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">医師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">7300000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">札幌</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">健一</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">恵子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">33</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">看護師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">翔</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">27</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">プログラマー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">神戸</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">茜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">販売員</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3200000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">仙台</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">隆</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">弁護士</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">横浜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">葵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">研究者</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">千葉</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">10</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">三郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
</tbody>
</table>
<h2><span id="toc8">Pandas concatで横結合する (axis=1)</span></h2>

<p>次に、データフレームを横方向（列方向）に結合する方法を見ていきましょう。これは、既存のデータフレームに新しい列を追加するイメージです。<code>pd.concat()</code> 関数で <code>axis=1</code> を指定します。</p>

<p>【例】インデックスを振り直して縦結合したデータフレーム <code>df3</code> に、新しい列「兄弟数」を含むデータフレーム <code>df4</code> を横（列方向）に結合します。</p>

<h3><span id="toc9">追加データの作成</span></h3>

<p>以下のコードで、横結合するための新しい列データを含むデータフレーム <code>df4</code> を作成します。このデータフレームの行数は、結合元の <code>df3</code> と同じになるように作成しています。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
df4 = pd.DataFrame({
    &#x27;兄弟数&#x27;: [0,2,1,0,3,1,1,1,0,2,0]
})

df4
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">兄弟数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">10</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
</tbody>
</table>
<h3><span id="toc10">横に結合</span></h3>

<p><code>pd.concat()</code> 関数で <code>axis=1</code> と指定することで、データフレームを横方向（列方向）に結合します。このとき、デフォルトでは<strong>インデックス（行を識別するラベルや番号）が一致する行同士</strong>が結合されます。今回の例では、<code>df3</code> と <code>df4</code> は <code>ignore_index=True</code> で作成された新しい連番インデックスを持っており、行数も一致しているため、それぞれのインデックスが一致する行が正しく結合され、新しい列「兄弟数」が追加されていることがわかります。</p>

<p>もし、結合するデータフレーム間でインデックスが一致しない行や、一方にしか存在しない行がある場合、対応する場所に <code>NaN</code> が挿入されます。横結合では、<strong>結合元のデータフレームのインデックスが揃っていることが重要</strong>です。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
df5 = pd.concat([df3, df4], axis=1)
df5
</code>
</pre>
<table border="1" class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">職業</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年収（円）</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">居住地</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">勤続年数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">兄弟数</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">太郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">23</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">エンジニア</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">花子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">デザイナー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">次郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">教師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4900000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">名古屋</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">美香</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">医師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">7300000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">札幌</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">4</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">健一</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">5</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">恵子</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">33</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">看護師</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">6</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">翔</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">27</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">プログラマー</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">神戸</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">7</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">茜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">販売員</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3200000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">仙台</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">8</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">隆</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">弁護士</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">横浜</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">9</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">葵</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">研究者</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">千葉</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">10</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">三郎</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">学生</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">東京</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
</tr>
</tbody>
</table>
<h2><span id="toc11">筆者の体験談：Pandas concatでやってしまった失敗</span></h2>

<p>はじめてPandas concatを使ったとき、「縦結合と横結合の切り替えにはaxisの指定が必要」というのを見逃してしまい、横に結合したつもりが縦にずれてしまったということがありました。</p>

<p>さらに、インデックスを意識せずに結合してしまい、同じインデックス番号が混在して重複データのように見えたり、後の処理でindexを使うときにバグを引き起こした経験があります。</p>

<p>改善策：結合時には必ず次の2点を確認しています：</p>

<p>axis=0（縦）かaxis=1（横）か
ignore_index=Trueをつけるべきかどうか
また、出力結果をdf（データフレーム名）.head()で直後に確認する癖をつけるようになってから、トラブルは激減しました。</p>

<h2><span id="toc12">Pandas concat 実行時によく発生するエラーとその対処法</span></h2>

<p><code>pd.concat</code> は便利な関数ですが、使い方によっては予期せぬエラーや問題が発生することがあります。ここでは、よく遭遇するケースとその対処法をいくつか紹介します。</p>

<h3><span id="toc13">1. 列の不一致による問題</span></h3>

<p>縦方向に結合（<code>axis=0</code>）する場合、結合するデータフレーム間で列名が一致しない場合、<code>concat</code> はエラーとはせず、一致しない列をそのまま結合し、対応する行に <code>NaN</code>（欠損値）を挿入します。これはエラーではありませんが、意図しない結果になる可能性があります。</p>

<p><strong>例:</strong></p>

<p><code>df_missing</code> には存在するが <code>df</code> には存在しない列があった場合など。</p>

<p><strong>対処法:</strong></p>

<ul>
<li><strong>結合前に列を揃える:</strong> 結合する前に、不要な列を削除したり、必要な列を追加して名前を一致させたりします。</li>
<li><strong>必要な列のみを選択して結合する:</strong> 結合したい列だけを選択して結合し、後で必要に応じて他の列を結合します。</li>
</ul>

<h3><span id="toc14">2. インデックスの重複による問題 (axis=0, ignore_index=False の場合)</span></h3>

<p>縦方向に結合（<code>axis=0</code>）し、<code>ignore_index=False</code>（デフォルト）の場合、結合元のデータフレームのインデックスがそのまま引き継がれます。元のデータフレームで同じインデックスがある場合、結合後もインデックスが重複します。これはエラーにはなりませんが、後の処理でインデックスをキーとしてデータを操作する際に問題を引き起こす可能性があります。</p>

<p><strong>例:</strong></p>

<p><code>df</code> と <code>df1</code> を <code>ignore_index=False</code> で結合した <code>df2</code> では、インデックス <code>0</code> が重複しています。</p>

<p><strong>対処法:</strong></p>

<ul>
<li><strong><code>ignore_index=True</code> を指定する:</strong> 結合後に新しい連番のインデックスを振り直すことで、インデックスの重複を防ぎます。これが最も一般的な対処法です。</li>
<li><strong>結合前にインデックスをリセットする:</strong> <code>reset_index()</code> メソッドを使って、結合前に各データフレームのインデックスをリセットします。</li>
<li><strong>インデックスに名前をつける:</strong> <code>df.index.name = '元のインデックス'</code> のようにインデックスに名前をつけ、結合後にその列を利用することもできます。</li>
</ul>

<h3><span id="toc15">3. 横結合 (axis=1) 時の行数の不一致</span></h3>

<p>横方向に結合（<code>axis=1</code>）する場合、デフォルトではインデックスが一致する行同士が結合されます。結合するデータフレーム間でインデックスが一致しない行や、一方にしか存在しない行がある場合、対応する場所に <code>NaN</code> が挿入されます。行数が完全に一致しない場合も、不足している部分に <code>NaN</code> が発生します。</p>

<p><strong>例:</strong></p>

<p><code>df3</code> (11行) と <code>df4</code> (11行) は行数が一致していたため <code>NaN</code> は発生しませんでしたが、もし <code>df4</code> が10行しかなかった場合、最後の行に <code>NaN</code> が発生します。</p>

<p><strong>対処法:</strong></p>

<ul>
<li><strong>結合前に行数を揃える:</strong> 結合するデータフレームの行数やインデックスを事前に確認し、必要に応じてフィルタリングやパディングを行います。</li>
<li><strong>インデックスをキーとして <code>merge</code> を使う:</strong> インデックスをキーとして厳密に結合したい場合は、<code>concat</code> の代わりに <code>merge</code> 関数を <code>left_index=True, right_index=True</code> と指定して使用することを検討します。<code>merge</code> なら、<code>how</code> 引数で結合方法（内部結合、外部結合など）を細かく制御できます。</li>
</ul>

<p>これらのエラーや問題は、<code>concat</code> 関数の <code>axis</code> と <code>ignore_index</code> 引数の挙動、そして結合するデータフレームの構造（列名、インデックス、行数）を理解することで、適切に対処・回避できます。結合後は必ず <code>head()</code> などで結果を確認する習慣をつけることが重要です。</p>

<h2><span id="toc16">実務シナリオ：複数の CSV ファイルをまとめて結合する</span></h2>
<p>実際のデータ分析では、複数のファイルに分割されたデータを一つにまとめてから分析を始めるケースがよくあります。例えば、月ごとに保存された売上データや、日ごとのログデータなどです。</p>

<p>このような場合、一つずつファイルを読み込んで concat するのは大変です。Pandas と Python の pathlib ライブラリを組み合わせることで、指定したフォルダ内の複数の CSV ファイルを効率的に読み込み、一気に縦方向に結合することができます。</p>

<p>ここでは、「Google Drive の特定のフォルダ（例: My Drive/データ）」にある全ての CSV ファイルを読み込み、一つのデータフレームに結合するシナリオを想定します。</p>

<p>以下のコードを実行すると、まず Google Drive に接続し、指定したフォルダ内の CSV ファイルをリストアップします。その後、それぞれのファイルを読み込み、pd.concat を使ってまとめて縦方向に結合します。ignore_index=True を指定することで、結合後のデータフレームのインデックスを振り直します。</p>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# ①googleドライブに接続する
from google.colab import drive
drive.mount('/content/drive')</code>
</pre>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
import pandas as pd
from pathlib import Path</code>
</pre>

<pre class="language-python" data-prismjs-copy>
<code class="language-python">
# ① フォルダパスを設定（「My Drive/データ」フォルダ内の CSV 全て）
folder = Path('/content/drive/My Drive/')

# ② glob で拡張子 .csv のファイル一覧を取得
csv_files = list(folder.glob('*.csv'))

# ③ 各ファイルを DataFrame に読み込み→リスト化
dfs = [pd.read_csv(fp) for fp in csv_files]

# ④ concat で縦方向に一気に結合。横結合の場合は（pd.concat(dfs, ignore_index=True,axis=1)）
df_all = pd.concat(dfs, ignore_index=True)

# 確認
df_all.head()</code>
</pre>



<div class="colab-df-container" id="df-20f7df04-e446-4a47-869c-1fc051746b32">
<div>
<style scoped="">
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">Product</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">Sales</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">Date</th>
</tr>
</thead>
<tbody>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02-10</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">1</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">250</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-02-25</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">2</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">100</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01-15</td>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">3</th>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">150</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2023-01-20</td>
</tr>
</tbody>
</table>
</div>


<!-- 縦結合、横結合の画像 -->
<figure>
  <img src="https://pythondatalab.com/wp-content/uploads/2025/07/csv_concat.png" 
       alt="Pandas concatによるcsvファイルの一括結合を示した図。データの縦結合をしている様子が視覚化されている。" 
       width="800" height="500" loading="lazy" decoding="async" />
  <figcaption>図：google driveのフォルダ内にある全csvファイルをPandas concat で縦結合</figcaption>
</figure>


<p>▶️ googleドライブへの接続方法や、csvファイルの読み込み等については下記で解説しています。</p>
<p><a href="https://pythondatalab.com/pandas-read-csv/">Pandas CSV入門|Google Colabでread_csvを使ったファイル読み込み＆保存を徹底解説</a></p>


<h2><span id="toc17">まとめ</span></h2>

<p>この記事では、Pandas の<code>concat</code>関数を使ったデータフレームの縦結合・横結合の方法を解説しました。結合時には<code>axis</code>引数と<code>ignore_index</code>引数を適切に使うことが重要です。</p>
<p>また、実務で役立つテクニックとして、<code>pathlib</code>ライブラリと組み合わせて特定のフォルダ内の複数のCSVファイルを一気に読み込み、<code>pd.concat</code>でまとめて縦方向に結合する方法も紹介しました。</p>
<p>結合方法について、改めてまとめましょう。</p><!DOCTYPE html>
<html>
<head>
<title>DataFrame結合方法</title>
<style>
  table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
    font-family: sans-serif;
  }
  th, td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
  }
  th {
    background-color: #f2f2f2;
    font-weight: bold;
  }
</style>
</head>
<body>

<h1>DataFrame結合方法</h1>

<table>
  <thead>
    <tr>
      <th>方法</th>
      <th>関数</th>
      <th>メリット</th>
      <th>デメリット・注意点</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>結合 (インデックス維持)</td>
      <td>pd.concat([df1, df2])</td>
      <td>元データのインデックス情報を保持できる。</td>
      <td>結合先でインデックスが重複している場合、結合後も重複し、後の処理で問題を起こす可能性がある。</td>
    </tr>
    <tr>
      <td>結合 (インデックス振り直し)</td>
      <td>pd.concat([df1, df2], ignore_index=True)</td>
      <td>新しい連番インデックスになり、データ整理が容易。</td>
      <td>元データのインデックス情報は失われる。</td>
    </tr>
    <tr>
      <td>結合</td>
      <td>pd.concat([df1, df2], axis=1)</td>
      <td>異なる列情報をデータフレームで結合できる。</td>
      <td>結合するデータフレームの行数が一致しない場合、不足部分にNaNが発生する。インデックス（行を識別するラベルや番号）が一致しないと意図しない結合になる。</td>
    </tr>

  </tbody>
</table>

</body>
</html>
<p>データ結合はデータ分析の基礎となる重要なステップです。今回学んだ<code>concat</code>関数と、<code>axis</code>や<code>ignore_index</code>といった引数の使い方をマスターして、効率的なデータ前処理を進めましょう！</p>

<article><!-- ② 関連記事セクション -->
<section class="related-posts">


<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ --></p>
<p><style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style></p>
<div class="related-box">
<h3><span id="toc18">関連記事</span></h3>
<ul>
<li style="list-style-type: none;">
<ul>
<li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
<li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li>
</ul>
</li>
</ul>
</div>
<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ --></p>


<!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ -->
<p><style>
  /* ここだけに効く最小リセット */
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }
  .pdl-series-nav a {
    display: inline !important;
    margin: 0 !important;
    padding: 0 !important;
    white-space: normal !important;
  }
  /* 念のため画像リンク等のブロック化も無効化 */
  .pdl-series-nav a img { display: inline !important; }
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ --><p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>
</div>



<script>Prism.highlightAll();</script>
</body>
</html>



<p class="wp-block-paragraph"></p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-concat/">Pandas concat完全ガイド｜複数CSVからDataFrameを縦横結合する方法</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-concat/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas 並び替え（sort）入門｜sort_values・sort_indexの違いと複数列ソート</title>
		<link>https://pythondatalab.com/pandas-sort/</link>
					<comments>https://pythondatalab.com/pandas-sort/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Mon, 21 Apr 2025 15:17:00 +0000</pubDate>
				<category><![CDATA[集計・変形]]></category>
		<guid isPermaLink="false"></guid>

					<description><![CDATA[<p>  💡 Pandas DataFrame入門シリーズ このページは「Pandas DataFrame入門」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。 今回は、Pythonのデータ分析ライブラリ [&#8230;]</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-sort/">pandas 並び替え（sort）入門｜sort_values・sort_indexの違いと複数列ソート</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[<div id="top"> </div>
<p><!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ --></p>
<p><style>
  /* ここだけに効く最小リセット */<br />
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }<br />
  .pdl-series-nav a {<br />
    display: inline !important;<br />
    margin: 0 !important;<br />
    padding: 0 !important;<br />
    white-space: normal !important;<br />
  }<br />
  /* 念のため画像リンク等のブロック化も無効化 */<br />
  .pdl-series-nav a img { display: inline !important; }<br />
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<p><!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ --></p>
<p>今回は、Pythonのデータ分析ライブラリ「Pandas」で、<strong>データフレームの並び替え</strong>（sort）方法について解説します。</p>

  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-15" checked><label class="toc-title" for="toc-checkbox-15">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">1. サンプルデータの作成</a></li><li><a href="#toc2" tabindex="0">2. インデックス順に並び替え（sort_index）</a><ol><li><a href="#toc3" tabindex="0">インデックスを降順にする</a></li></ol></li><li><a href="#toc4" tabindex="0">3. 値で並び替え（sort_values）</a></li><li><a href="#toc5" tabindex="0">筆者の体験談：sortでハマった失敗と改善策</a></li><li><a href="#toc6" tabindex="0">まとめ</a></li><li><a href="#toc7" tabindex="0">次回予告</a><ol><li><a href="#toc8" tabindex="0">関連記事</a></li><li><a href="#toc9" tabindex="0">sort_values()とsort_index()の違いは？</a></li><li><a href="#toc10" tabindex="0">複数列でソートするには？</a></li><li><a href="#toc11" tabindex="0">降順に並べ替える方法は？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">1. サンプルデータの作成</span></h2>
<pre><code>import pandas as pd

df = pd.DataFrame({
    "名前": ["太郎", "花子", "次郎", "美香", "健一", "恵子", "翔", "茜", "隆", "葵"],
    "年齢": [23, 29, 35, 42, 18, 33, 27, 24, 31, 30],
    "職業": ["エンジニア", "デザイナー", "教師", "医師", "学生", "看護師", "プログラマー", "販売員", "弁護士", "研究者"],
    "年収（円）": [4500000, 5500000, 4900000, 7300000, 0, 4000000, 6000000, 3200000, 8000000, 5800000],
    "居住地": ["東京", "大阪", "名古屋", "札幌", "福岡", "東京", "神戸", "仙台", "横浜", "千葉"],
    "勤続年数": [2, 4, 10, 15, 1, 5, 3, 1, 12, 8]
})

df</code></pre>
<p>出力結果：</p>
<table>
<thead>
<tr>
<th>インデックス</th>
<th>名前</th>
<th>年齢</th>
<th>職業</th>
<th>年収（円）</th>
<th>居住地</th>
<th>勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>太郎</td>
<td>23</td>
<td>エンジニア</td>
<td>4500000</td>
<td>東京</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>花子</td>
<td>29</td>
<td>デザイナー</td>
<td>5500000</td>
<td>大阪</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>次郎</td>
<td>35</td>
<td>教師</td>
<td>4900000</td>
<td>名古屋</td>
<td>10</td>
</tr>
<tr>
<td>3</td>
<td>美香</td>
<td>42</td>
<td>医師</td>
<td>7300000</td>
<td>札幌</td>
<td>15</td>
</tr>
<tr>
<td>4</td>
<td>健一</td>
<td>18</td>
<td>学生</td>
<td>0</td>
<td>福岡</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>恵子</td>
<td>33</td>
<td>看護師</td>
<td>4000000</td>
<td>東京</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>翔</td>
<td>27</td>
<td>プログラマー</td>
<td>6000000</td>
<td>神戸</td>
<td>3</td>
</tr>
<tr>
<td>7</td>
<td>茜</td>
<td>24</td>
<td>販売員</td>
<td>3200000</td>
<td>仙台</td>
<td>1</td>
</tr>
<tr>
<td>8</td>
<td>隆</td>
<td>31</td>
<td>弁護士</td>
<td>8000000</td>
<td>横浜</td>
<td>12</td>
</tr>
<tr>
<td>9</td>
<td>葵</td>
<td>30</td>
<td>研究者</td>
<td>5800000</td>
<td>千葉</td>
<td>8</td>
</tr>
</tbody>
</table>
<h2><span id="toc2">2. インデックス順に並び替え（sort_index）</span></h2>
<pre><code># インデックスを昇順にソート
df.sort_index()</code></pre>
<p>※この場合、もともと昇順なので結果は変わりません。</p>
<h3><span id="toc3">インデックスを降順にする</span></h3>
<pre><code># インデックスを降順にソート
df.sort_index(ascending=False)</code></pre>
<p>出力結果：</p>
<table>
<thead>
<tr>
<th>インデックス</th>
<th>名前</th>
<th>年齢</th>
<th>職業</th>
<th>年収（円）</th>
<th>居住地</th>
<th>勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<td>9</td>
<td>葵</td>
<td>30</td>
<td>研究者</td>
<td>5800000</td>
<td>千葉</td>
<td>8</td>
</tr>
<tr>
<td>8</td>
<td>隆</td>
<td>31</td>
<td>弁護士</td>
<td>8000000</td>
<td>横浜</td>
<td>12</td>
</tr>
<tr>
<td>7</td>
<td>茜</td>
<td>24</td>
<td>販売員</td>
<td>3200000</td>
<td>仙台</td>
<td>1</td>
</tr>
<tr>
<td>6</td>
<td>翔</td>
<td>27</td>
<td>プログラマー</td>
<td>6000000</td>
<td>神戸</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>恵子</td>
<td>33</td>
<td>看護師</td>
<td>4000000</td>
<td>東京</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>健一</td>
<td>18</td>
<td>学生</td>
<td>0</td>
<td>福岡</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>美香</td>
<td>42</td>
<td>医師</td>
<td>7300000</td>
<td>札幌</td>
<td>15</td>
</tr>
<tr>
<td>2</td>
<td>次郎</td>
<td>35</td>
<td>教師</td>
<td>4900000</td>
<td>名古屋</td>
<td>10</td>
</tr>
<tr>
<td>1</td>
<td>花子</td>
<td>29</td>
<td>デザイナー</td>
<td>5500000</td>
<td>大阪</td>
<td>4</td>
</tr>
<tr>
<td>0</td>
<td>太郎</td>
<td>23</td>
<td>エンジニア</td>
<td>4500000</td>
<td>東京</td>
<td>2</td>
</tr>
</tbody>
</table>
<h2><span id="toc4">3. 値で並び替え（sort_values）</span></h2>
<pre><code># "居住地"を降順に並び替え
df.sort_values(by='居住地', ascending=False)</code></pre>
<p>出力結果：</p>
<table>
<thead>
<tr>
<th>インデックス</th>
<th>名前</th>
<th>年齢</th>
<th>職業</th>
<th>年収（円）</th>
<th>居住地</th>
<th>勤続年数</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>美香</td>
<td>42</td>
<td>医師</td>
<td>7300000</td>
<td>札幌</td>
<td>15</td>
</tr>
<tr>
<td>2</td>
<td>次郎</td>
<td>35</td>
<td>教師</td>
<td>4900000</td>
<td>名古屋</td>
<td>10</td>
</tr>
<tr>
<td>5</td>
<td>恵子</td>
<td>33</td>
<td>看護師</td>
<td>4000000</td>
<td>東京</td>
<td>5</td>
</tr>
<tr>
<td>8</td>
<td>隆</td>
<td>31</td>
<td>弁護士</td>
<td>8000000</td>
<td>横浜</td>
<td>12</td>
</tr>
<tr>
<td>9</td>
<td>葵</td>
<td>30</td>
<td>研究者</td>
<td>5800000</td>
<td>千葉</td>
<td>8</td>
</tr>
<tr>
<td>1</td>
<td>花子</td>
<td>29</td>
<td>デザイナー</td>
<td>5500000</td>
<td>大阪</td>
<td>4</td>
</tr>
<tr>
<td>6</td>
<td>翔</td>
<td>27</td>
<td>プログラマー</td>
<td>6000000</td>
<td>神戸</td>
<td>3</td>
</tr>
<tr>
<td>7</td>
<td>茜</td>
<td>24</td>
<td>販売員</td>
<td>3200000</td>
<td>仙台</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>太郎</td>
<td>23</td>
<td>エンジニア</td>
<td>4500000</td>
<td>東京</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>健一</td>
<td>18</td>
<td>学生</td>
<td>0</td>
<td>福岡</td>
<td>1</td>
</tr>
</tbody>
</table>
<h2><span id="toc5">筆者の体験談：sortでハマった失敗と改善策</span></h2>
<p>初めて<code>sort_values</code>を使ったとき、私は次のように複数列を並び替えようとして、うまく動作しないことがありました。</p>
<pre><code># 誤り：列名を文字列で1つだけ渡していたつもりが意図が伝わっていなかった
# 想定では名前で昇順・年収で降順にしたかった

# 正しくはリストと辞書で複数指定する必要があった
# 改善後：
df.sort_values(by=['名前', '年収（円）'], ascending=[True, False])</code></pre>
<p>また、<code>sort_index()</code>と<code>sort_values()</code>を混同して、思ったように値のソートができず、「あれ？インデックスが変わらない？」と混乱した経験もあります。</p>
<p><strong>改善策：</strong> 並び替えたい「対象」がインデックスか列かを明確に区別するようにしました。<br />「index → sort_index」「値 → sort_values」とメモしてIDEの横に貼ったのが意外と効果的でした。</p>
<p><em>ソートは簡単なようで、細かい指定方法の違いで戸惑うこともあります。小さな違和感を大切にして調べる習慣が大切です。</em></p>
<p>▶️ sort_indexやsort_valuesの公式ドキュメントも参考にしてください：<br /><a rel="noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" target="_blank">pandas DataFrame sort_index Documentation</a></p>
<p><a rel="noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" target="_blank">pandas DataFrame sort_values Documentation</a></p>
<h2><span id="toc6">まとめ</span></h2>
<ul>
<li><code>sort_index()</code>：インデックス順に並び替える</li>
<li><code>sort_values(by='列名')</code>：指定した列の値で並び替える</li>
<li>昇順（ascending=True）、降順（ascending=False）を切り替えられる</li>
</ul>
<h2><span id="toc7">次回予告</span></h2>
<p>次回は、<strong>データフレームを結合（concat）</strong>について、わかりやすく解説していきます！<br /><!-- ① シリーズナビゲーション --></p>
<article><!-- ② 関連記事セクション -->
<section class="related-posts">
<article><!-- ① シリーズナビゲーション --></article>
</section>
</article>
<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）▼▼▼ --></p>
<p><style> .related-box { border: 2px solid #0073aa; border-radius: 10px; padding: 1em 1.2em; margin-top: 2em; background: #f8faff; } .related-box h3 { margin-top: 0; color: #0073aa; } .related-box ul { list-style-type: none; margin: 0; padding: 0; } .related-box li { margin: 0.4em 0; } .related-box a { text-decoration: none; color: #333; } .related-box a:hover { text-decoration: underline; color: #0073aa; } </style></p>
<div class="related-box">
<h3><span id="toc8">関連記事</span></h3>
<ul>
<li style="list-style-type: none;">
<ul>
<li><a href="https://pythondatalab.com/category/pandas/preprocessing/">◀ データ抽出・前処理：loc, iloc, isin, dropの使い方</a></li>
<li><a href="https://pythondatalab.com/category/pandas/visualization/">▶ MatplotlibでPandasデータを可視化する方法</a></li>
</ul>
</li>
</ul>
</div>
<p><!-- ▼▼▼ 関連記事ボックス 共通スタイル（集計・変形）終了▼▼▼ --></p>
<p><!-- ▼▼▼ Pandasシリーズナビ（開始） ▼▼▼ --></p>
<p><style>
  /* ここだけに効く最小リセット */<br />
  .pdl-series-nav p { margin: 0; line-height: 1.7; white-space: normal; }<br />
  .pdl-series-nav a {<br />
    display: inline !important;<br />
    margin: 0 !important;<br />
    padding: 0 !important;<br />
    white-space: normal !important;<br />
  }<br />
  /* 念のため画像リンク等のブロック化も無効化 */<br />
  .pdl-series-nav a img { display: inline !important; }<br />
</style></p>
<div id="pandas-series-nav" class="pdl-series-nav" style="clear: both; overflow: auto; position: relative; width: 100%; max-width: 100%; box-sizing: border-box; border: 2px solid #4db6ac; background: #eafaf8; padding: 14px 18px; border-radius: 10px; margin: 1.5em 0; box-shadow: 0 3px 6px rgba(0,0,0,0.05); transition: box-shadow .3s ease;">
<p style="margin: 0 0 6px 0; font-weight: 600; color: #00695c; font-size: 1.05em;">💡 Pandas DataFrame入門シリーズ</p>
<p>このページは「<a style="color: #00796b; text-decoration: underline; font-weight: 500;" href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a>」シリーズの一部です。データの作成から結合・集計までを体系的に学べます。</p>
</div>
<p><!-- ▲▲▲ Pandasシリーズナビ（終了） ▲▲▲ --></p>
<p style="text-align: center; margin-top: 2em;"><a href="#top">▲ ページトップへ戻る</a></p>

<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1760196578156" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc9">sort_values()とsort_index()の違いは？</span></h3>
<div class="rank-math-answer ">

<p>sort_values()は値でソート、sort_index()はインデックス順でソートします。</p>

</div>
</div>
<div id="faq-question-1760196590949" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc10">複数列でソートするには？</span></h3>
<div class="rank-math-answer ">

<p><code>df.sort_values(['列1', '列2'])</code> のようにリストで列を指定します。</p>

</div>
</div>
<div id="faq-question-1760196604818" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc11">降順に並べ替える方法は？</span></h3>
<div class="rank-math-answer ">

<p><code>ascending=False</code> を指定します。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-sort/">pandas 並び替え（sort）入門｜sort_values・sort_indexの違いと複数列ソート</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pythondatalab.com/pandas-sort/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
