<?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>Python Data Lab（Pythonデータラボ）</title>
	<atom:link href="https://pythondatalab.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://pythondatalab.com</link>
	<description>Python初心者向けに、わかりやすいデータ分析の解説を提供します。</description>
	<lastBuildDate>Sun, 10 May 2026 15:42:50 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://pythondatalab.com/wp-content/uploads/2025/12/cropped-rogo-32x32.png</url>
	<title>Python Data Lab（Pythonデータラボ）</title>
	<link>https://pythondatalab.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>


<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 between()の使い方｜数値・日付を範囲で抽出する方法</title>
		<link>https://pythondatalab.com/pandas-between/</link>
					<comments>https://pythondatalab.com/pandas-between/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 09 May 2026 15:40:35 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2068</guid>

					<description><![CDATA[<p>pandasのbetween()で数値や日付を範囲抽出する方法を初心者向けに解説。判定から行抽出までの流れ、inclusive、欠損値、query()やcut()との違いも整理します。</p>
<p>パーマリンク案</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-between/">pandas between()の使い方｜数値・日付を範囲で抽出する方法</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 code[class*="language-"] {
    white-space: pre;
  }
  .colab-article .wp-block-table {
    margin: 0.8em 0;
  }
  .colab-article .wp-block-table th,
  .colab-article .wp-block-table td {
    vertical-align: top;
  }
  .colab-figure {
    margin: 1em 0;
  }
  .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>

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


<p>CSVを読み込んだあと、DataFrameの中から <strong>「一定の範囲に入る行だけ」</strong> を取り出したいことがあります。</p>
<p>たとえば、次のような場面です。</p>
<ul>
<li>売上が1000円〜5000円の商品だけ見たい</li>
<li>2026年1月の注文だけ確認したい</li>
<li>年齢が20歳〜40歳の人だけ抽出したい</li>
</ul>
<p>このような <strong>数値や日付の範囲で行を絞り込む処理</strong> に使えるのが、Pandasの <code>between()</code> です。</p>
<p><code>between()</code> を使うと、たとえば「売上が1000円以上5000円以下の行」を、次のように短く書けます。</p>
<p><code>df[df["売上"].between(1000, 5000)]</code></p>
<p>つまり、<code>between()</code> は <strong>1つの列を「下限〜上限」の範囲で抽出したいときに使う方法</strong> です。</p>
<p>この記事では、<code>between()</code> を使って、数値や日付の範囲で行を抽出する方法を、サンプルデータで順番に確認します。あわせて、範囲の始まりと終わりを含めるかどうか、<code>between()</code> と同じ範囲抽出を、<code>&gt;=</code>・<code>&lt;=</code> や <code>query()</code> で書く方法も確認します。</p>
<p>また、範囲に関係する処理として <code>cut()</code> もあります。ただし、<code>cut()</code> は <code>between()</code> と同じ結果を出すための方法ではありません。<code>between()</code> は「範囲に入る行を抽出する」処理、<code>cut()</code> は「値を区間に分ける」処理です。この違いは、本文後半で具体例を使って確認します。</p>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を順番に確認します。</p>
<ul>
<li><code>between()</code> とは何か、範囲抽出の基本</li>
<li>数値を範囲で抽出する方法</li>
<li>日付を範囲で抽出する方法</li>
<li><code>inclusive</code> で数値や日付の範囲の境界値を含める・含めない設定</li>
<li><code>between()</code> と <code>&gt;=</code>・<code>&lt;=</code>・<code>query()</code>・<code>cut()</code> の違い</li>
<li>範囲抽出後に集計・可視化へつなげる考え方</li>
</ul>

<h2><span id="toc2">やりたいこと別：between()を使う場面</span></h2>
<p><code>between()</code> は、<strong>1つの列を「下限〜上限」の範囲で絞りたいとき</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; border: 1px solid #ddd;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う方法</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">例</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>between()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上1000円〜5000円</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>between()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026年1月の注文</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>query()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>&gt;=</code>・<code>&lt;=</code> や <code>query()</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>cut()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上を低価格・中価格・高価格に分類</td>
</tr>
</tbody>
</table>
<p><code>between()</code> は、連続した範囲で行を絞り込むときに向いています。</p>
<p>候補リストから選ぶ場合や、文字列を含む行を探す場合は、後半の「between()を使わない場面」で軽く整理します。</p>

<h2><span id="toc3">サンプルデータを用意する</span></h2>
<p>ここでは、ECサイトの注文データを例にします。</p>
<p><code>売上</code> と <code>注文日</code> を使って、数値と日付の範囲抽出を確認していきます。</p>

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

data = {
    &quot;注文日&quot;: [&quot;2026-01-03&quot;, &quot;2026-01-08&quot;, &quot;2026-01-15&quot;, &quot;2026-01-28&quot;, &quot;2026-02-04&quot;, &quot;2026-02-12&quot;, &quot;日付不明&quot;],
    &quot;商品&quot;: [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;, &quot;USBメモリ&quot;, &quot;モニター&quot;, &quot;Webカメラ&quot;, &quot;ケーブル&quot;],
    &quot;カテゴリ&quot;: [&quot;PC&quot;, &quot;周辺機器&quot;, &quot;周辺機器&quot;, &quot;周辺機器&quot;, &quot;PC&quot;, &quot;周辺機器&quot;, &quot;周辺機器&quot;],
    &quot;売上&quot;: [120000, 1000, 4800, 980, 5000, None, 3200]
}

df = pd.DataFrame(data)
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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">2026-01-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-01-28</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">980.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">2026-02-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Webカメラ</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;">NaN</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;">ケーブル</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>この時点では、<code>注文日</code> は文字列として入っています。日付の範囲抽出をするときは、あとで <code>pd.to_datetime()</code> を使って日付型に変換します。</p>

<h2><span id="toc4">数値を範囲で抽出する方法</span></h2>
<p>ここからは、<code>売上</code> 列を使って <code>between()</code> の動きを確認します。</p>
<p><code>between()</code> は、いきなり行を取り出すのではなく、まず各行が範囲内かどうかを判定します。</p>

<h3><span id="toc5">まずbetween()で範囲内かどうかを判定する</span></h3>
<p><code>between()</code> は、最初に各行の値が指定した範囲に入っているかどうかを、<code>True</code> / <code>False</code> で判定します。</p>
<p>たとえば、<code>売上</code> が1000円以上5000円以下かどうかを判定してみます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;売上&quot;].between(1000, 5000)
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">False</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;">True</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;">True</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;">False</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;">True</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;">False</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;">True</td>
    </tr>
  </tbody>
</table>

<p><code>True</code> は範囲内、<code>False</code> は範囲外という意味です。</p>
<p>この判定結果を使うと、次のステップで <code>True</code> の行だけを抽出できます。</p>

<h3><span id="toc6">判定結果を使って行を抽出する</span></h3>
<p>範囲内かどうかを判定できたら、その条件を <code>df[...]</code> に入れます。</p>
<p>これで、<code>売上</code> が1000円以上5000円以下の行だけを抽出できます。</p>

<pre class="line-numbers"><code class="language-python">売上範囲内 = df[df[&quot;売上&quot;].between(1000, 5000)]
売上範囲内
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">ケーブル</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>このコードでは、<code>売上</code> が1000円以上5000円以下の行だけが残ります。</p>
<p>ポイントは、<strong>1000円ちょうどの行も、5000円ちょうどの行も含まれる</strong>ことです。<code>between()</code> は、初期設定では両端の値を含みます。</p>

<p><code>between()</code> は、売上だけでなく、年齢・点数・価格など、範囲で絞りたい数値列にも同じように使えます。</p>

<h2><span id="toc7">日付を範囲で抽出する方法</span></h2>
<p><code>between()</code> は、数値だけでなく日付にも使えます。</p>
<p>ただし、CSVから読み込んだ日付列は、文字列のままになっていることがあります。日付の範囲抽出をする前に、<code>pd.to_datetime()</code> で日付型に変換しておきます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;注文日&quot;] = pd.to_datetime(df[&quot;注文日&quot;], errors=&quot;coerce&quot;)
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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">2026-01-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-01-28</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">980.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">2026-02-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Webカメラ</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;">NaN</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>このセルを実行すると、<code>df["注文日"]</code> は日付型に変換されます。</p>
<p>そのため、以降の <code>df</code> では、日付として変換できなかった <code>"日付不明"</code> は <code>NaT</code> と表示されます。</p>

<p><code>errors="coerce"</code> を指定すると、日付に変換できない値は <code>NaT</code> に変わります。</p>
<p>今回のデータでは、<code>"日付不明"</code> は日付として変換できません。<code>errors="coerce"</code> を指定しないとエラーになりますが、指定しておけば <code>NaT</code> に変換され、処理を続けられます。</p>
<p>次に、2026年1月1日から2026年1月31日までの注文だけを抽出します。</p>

<pre class="line-numbers"><code class="language-python">開始日 = pd.to_datetime(&quot;2026-01-01&quot;)
終了日 = pd.to_datetime(&quot;2026-01-31&quot;)

一月注文 = df[df[&quot;注文日&quot;].between(開始日, 終了日)]
一月注文
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">2026-01-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-01-28</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">980.0</td>
    </tr>
  </tbody>
</table>

<p>このように、<code>between()</code> を使うと、指定期間内の日付データだけを取り出せます。</p>
<p>日付の範囲抽出では、次の流れを意識すると安全です。</p>
<ol>
<li><code>pd.to_datetime()</code> で日付型に変換する</li>
<li>開始日と終了日を決める</li>
<li><code>between(開始日, 終了日)</code> で抽出する</li>
</ol>
<p>日付変換そのものを詳しく確認したい場合は、関連記事の <code>to_datetime()</code> を読むと理解しやすくなります。</p>

<p>抽出した結果は、必要な列だけ表示して確認すると見やすくなります。</p>

<pre class="line-numbers"><code class="language-python">一月注文[[&quot;注文日&quot;, &quot;商品&quot;, &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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">2026-01-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-01-28</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">980.0</td>
    </tr>
  </tbody>
</table>

<p>指定した日付範囲に入る行だけが残っていることを確認できます。</p>

<h2><span id="toc8">inclusiveで数値や日付の範囲の境界値を含める・含めない設定</span></h2>
<p><code>between()</code> は、境界値を含めるかどうかを <code>inclusive</code> で指定できます。</p>
<p>たとえば、1000円以上5000円以下なのか、1000円より大きく5000円未満なのかで、結果が変わります。</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; border: 1px solid #ddd;">書き方</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">意味</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">境界値1000</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">境界値5000</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>inclusive="both"</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>inclusive="left"</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>inclusive="right"</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>inclusive="neither"</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>
<p>まずは、初期設定と同じ <code>inclusive="both"</code> を確認します。</p>

<pre class="line-numbers"><code class="language-python">df[df[&quot;売上&quot;].between(1000, 5000, inclusive=&quot;both&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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>1000円ちょうど、5000円ちょうどの行がどちらも含まれます。</p>
<p>次に、両端を含めない <code>inclusive="neither"</code> を見てみましょう。</p>

<pre class="line-numbers"><code class="language-python">df[df[&quot;売上&quot;].between(1000, 5000, inclusive=&quot;neither&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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-15</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;">4800.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>この場合は、1000円ちょうどと5000円ちょうどの行は含まれません。</p>
<p>初心者がつまずきやすいのは、<strong>境界値を含むと思っていたのに含まれていない、またはその逆</strong>です。抽出条件を書くときは、「以上・以下」なのか「より大きい・未満」なのかを先に決めておきましょう。</p>

<h2><span id="toc9">範囲抽出で欠損値があるときの注意点</span></h2>
<p>ここまでで、数値と日付の範囲抽出を確認しました。</p>
<p>次に、抽出対象の列に欠損値がある場合の動きを確認します。</p>
<p><code>between()</code> では、<code>NaN</code> や日付型の欠損値は範囲内として扱われません。</p>
<p>実際に、<code>売上</code> が欠損している行がどう判定されるか確認してみましょう。</p>

<p>ここでは、欠損値がどのように判定されるかを見やすくするために、<code>商品</code>・<code>売上</code>・<code>範囲内</code> だけを並べた確認用のDataFrameを作ります。</p>
<p>元の <code>df</code> を変更しているわけではなく、判定結果を確認するための表です。</p>

<pre class="line-numbers"><code class="language-python">pd.DataFrame({
    &quot;商品&quot;: df[&quot;商品&quot;],
    &quot;売上&quot;: df[&quot;売上&quot;],
    &quot;範囲内&quot;: df[&quot;売上&quot;].between(1000, 5000)
})
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">範囲内</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;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">1000.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">4800.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">USBメモリ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">980.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">5000.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">Webカメラ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">3200.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</td>
    </tr>
  </tbody>
</table>

<p><code>売上</code> が欠損している行は、<code>範囲内</code> が <code>False</code> になります。</p>
<p>欠損値は、1000以上とも5000以下とも判断できないためです。欠損値をどう扱うかは、分析目的によって変わります。</p>

<h2><span id="toc10">between()と&gt;=・&lt;=・query()・cut()の違い</span></h2>
<p><code>between()</code> と似た処理は、比較演算子や <code>query()</code> でも書けます。また、範囲に関係するメソッドとして <code>cut()</code> もあります。</p>
<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; border: 1px solid #ddd;">比較対象</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う場面</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>between()</code>との違い</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>&gt;=</code>・<code>&lt;=</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>between()</code>のほうが範囲抽出の意図が読みやすい</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>query()</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>cut()</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>between()</code>は範囲に入る行を抽出、<code>cut()</code>は値を区間に分類</td>
</tr>
</tbody>
</table>
<p>同じ範囲条件を、<code>between()</code> と比較演算子で比べてみましょう。</p>

<pre class="line-numbers"><code class="language-python"># between()を使う書き方
df[df[&quot;売上&quot;].between(1000, 5000)]
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<pre class="line-numbers"><code class="language-python"># 比較演算子を使う書き方
df[(df[&quot;売上&quot;] &gt;= 1000) &amp; (df[&quot;売上&quot;] &lt;= 5000)]
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>1つの列を範囲で絞るだけなら、<code>between()</code> のほうが読みやすいことが多いです。</p>
<p>一方で、「売上が5000円以上」「カテゴリが周辺機器」「注文日が1月以降」のように複数条件を組み合わせる場合は、通常の条件式や <code>query()</code> も選択肢になります。</p>

<h3><span id="toc11">query()で書く場合</span></h3>
<p>同じ条件を <code>query()</code> で書くと、次のようになります。</p>

<pre class="line-numbers"><code class="language-python">df.query(&quot;1000 &lt;= 売上 &lt;= 5000&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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p><code>query()</code> は便利ですが、列名や文字列条件の書き方に慣れが必要です。</p>
<p>この記事では、まず <strong>1つの列を範囲で絞るなら <code>between()</code></strong> と覚えるのがおすすめです。</p>

<h3><span id="toc12">cut()は抽出ではなく分類に使う</span></h3>
<p><code>between()</code> と <code>cut()</code> は、どちらも「範囲」に関係しますが、役割は違います。</p>
<p><code>between()</code> は、範囲に合う行を残すための方法です。</p>

<pre class="line-numbers"><code class="language-python">df[df[&quot;売上&quot;].between(1000, 5000)]
</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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <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;">2026-01-08</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;">1000.0</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;">2026-01-15</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;">4800.0</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;">2026-02-04</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">NaT</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;">3200.0</td>
    </tr>
  </tbody>
</table>

<p>一方で、<code>cut()</code> は値を区間ごとのラベルに分けたいときに使います。ここでは違いを確認するために、軽く例だけ示します。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;売上帯&quot;] = pd.cut(
    df[&quot;売上&quot;],
    bins=[0, 1000, 5000, 200000],
    labels=[&quot;低め&quot;, &quot;中くらい&quot;, &quot;高め&quot;]
)

df[[&quot;商品&quot;, &quot;売上&quot;, &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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上帯</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;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.0</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;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000.0</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;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4800.0</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;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">980.0</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;">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;">5000.0</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;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Webカメラ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</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;">3200.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">中くらい</td>
    </tr>
  </tbody>
</table>

<p><code>cut()</code> は行を取り出すというより、値をカテゴリに分ける処理です。</p>
<p>今回の記事の主役は、あくまで <strong>範囲で行を抽出する <code>between()</code></strong> です。区間分けを詳しく学びたい場合は、<code>cut()</code> の記事に進むとよいです。</p>

<h3><span id="toc13">between()を使わない場面も確認しておく</span></h3>
<p><code>between()</code> は、数値や日付を「下限〜上限」の範囲で絞るときに使います。</p>
<p>一方で、次のような条件では、<code>between()</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; border: 1px solid #ddd;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う方法</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>isin()</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>str.contains()</code></td>
</tr>
</tbody>
</table>
<p>たとえば、商品名が「マウス」または「キーボード」の行を取り出したい場合は <code>isin()</code>、商品名に「PC」を含む行を探したい場合は <code>str.contains()</code> が向いています。</p>
<p>この記事では <code>between()</code> を中心に扱うため、<code>isin()</code> と <code>str.contains()</code> は詳しく扱いません。必要に応じて関連記事で確認してください。</p>

<h2><span id="toc14">抽出したデータを集計して確認する</span></h2>
<p><code>between()</code> は、抽出して終わりではありません。抽出したデータを集計すると、条件に合うデータの傾向を確認しやすくなります。</p>
<p>データ分析では、必要な行だけを取り出したあとに、件数を数えたり、カテゴリ別に集計したり、グラフにしたりすることが多いです。</p>
<p>ここでは、売上が1000円以上5000円以下の商品だけに絞ったあと、カテゴリ別に件数を数えてみます。</p>

<pre class="line-numbers"><code class="language-python">売上範囲内 = df[df[&quot;売上&quot;].between(1000, 5000)]

売上範囲内[&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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">count</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;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
    </tr>
  </tbody>
</table>

<p><code>value_counts()</code> を使うと、抽出後のデータにどのカテゴリが多いかを確認できます。</p>
<p>次に、カテゴリ別の売上合計も確認してみます。</p>

<pre class="line-numbers"><code class="language-python">売上範囲内.groupby(&quot;カテゴリ&quot;)[&quot;売上&quot;].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; border: 1px solid #ddd;"></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">PC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5000.0</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;">9000.0</td>
    </tr>
  </tbody>
</table>

<p>この流れは、実務でもよく使います。</p>
<p><strong>CSV読み込み → 型確認 → 必要な範囲で抽出 → 集計 → 可視化</strong> という流れの中で、<code>between()</code> は「必要な行だけを取り出す」ための前処理として使えます。</p>

<h3><span id="toc15">必要に応じてグラフで確認する</span></h3>
<p>集計結果は、必要に応じてグラフで確認できます。</p>
<p>本格的なグラフ調整はMatplotlibの記事で扱うため、ここでは「抽出後のデータを可視化につなげられる」ことだけ確認します。</p>

<pre class="line-numbers"><code class="language-python">!pip install japanize-matplotlib &gt; /dev/null

import matplotlib.pyplot as plt
import japanize_matplotlib

集計結果 = 売上範囲内.groupby(&quot;カテゴリ&quot;)[&quot;売上&quot;].sum()

集計結果.plot(kind=&quot;bar&quot;)
plt.title(&quot;カテゴリ別の売上合計&quot;)
plt.xlabel(&quot;カテゴリ&quot;)
plt.ylabel(&quot;売上&quot;)
plt.show()
</code></pre>
<figure class="colab-figure">
  <img decoding="async" src="images/figure1.png" alt="between()で抽出したデータをカテゴリ別に集計した棒グラフ">
  <figcaption>between()で抽出したデータをカテゴリ別に集計した棒グラフ</figcaption>
</figure>

<p><code>between()</code> で絞り込んだあとに集計・可視化すると、必要な範囲だけに注目してデータを見やすくなります。</p>
<p>たとえば、全体では高額商品の影響が大きすぎる場合でも、1000〜5000円の商品だけに絞ることで、中価格帯の商品傾向を確認しやすくなります。</p>

<h2><span id="toc16">よくあるミスと確認ポイント</span></h2>
<p><code>between()</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; border: 1px solid #ddd;">よくあるミス</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">原因</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">対策</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;"><code>pd.to_numeric()</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;">日付型ではなく文字列のまま</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>pd.to_datetime()</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>inclusive</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>NaN</code> や <code>NaT</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;">複数条件をすべてbetween()で書こうとする</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;">複数条件では AND/OR や <code>query()</code> も使う</td>
</tr>
</tbody>
</table>
<p>数値の範囲抽出では、必要に応じて先に数値型へ変換します。</p>

<p>数値の範囲抽出では、列が文字列になっている場合に <code>pd.to_numeric()</code> で数値型へ変換します。</p>
<p>日付の範囲抽出では、<code>pd.to_datetime()</code> で日付型へ変換してから <code>between()</code> を使います。</p>

<p><code>between()</code> は、基本的に1つの列を下限〜上限で絞るときに使います。</p>
<p>複数列にまたがる複雑な条件を扱う場合は、通常の条件式や <code>query()</code> も候補にしましょう。</p>

<h2><span id="toc17">between()は前処理・抽出で使う</span></h2>
<p><code>between()</code> は、集計や可視化の前に、必要な行だけを取り出すための処理です。</p>
<p>たとえば、次のような流れで使います。</p>
<p><code>CSV読み込み → 型の確認 → 数値・日付の変換 → 範囲抽出 → 集計 → 可視化</code></p>
<p>つまり、<code>between()</code> は、すべてのデータを見る前に、分析したい範囲に絞り込むための前処理として使えます。</p>

<h2><span id="toc18">まとめ：between()は数値・日付の範囲抽出を読みやすくする方法</span></h2>
<p>この記事では、Pandasの <code>between()</code> を使って、数値や日付の範囲で行を抽出する方法を解説しました。</p>
<p>ポイントを整理します。</p>
<ul>
<li><code>between()</code> は、1つの列を下限〜上限で絞りたいときに使う</li>
<li>数値だけでなく、日付の範囲抽出にも使える</li>
<li>初期設定では、両端の境界値を含む</li>
<li>数値や日付の範囲の境界値を含めるかどうかは <code>inclusive</code> で指定できる</li>
<li><code>NaN</code> や <code>NaT</code> は範囲内として扱われない</li>
<li>文字列の数字は <code>to_numeric()</code>、日付文字列は <code>to_datetime()</code> で整えてから使う</li>
<li>候補リストなら <code>isin()</code>、文字列検索なら <code>str.contains()</code>、区間分けなら <code>cut()</code> を使う</li>
<li>抽出後は <code>value_counts()</code> や <code>groupby()</code>、Matplotlib可視化へつなげると分析に活かしやすい</li>
</ul>
<p>まずは、<strong>「1つの列を下限〜上限で抽出したいときは <code>between()</code>」</strong> と覚えておくと、条件式を読みやすく書けるようになります。</p>

<h2><span id="toc19">次に読みたい関連記事</span></h2>
<p>範囲抽出の前後で使いやすい記事をまとめます。</p>
<ul>
<li><p><a href="https://pythondatalab.com/pandas-filtering/">pandas 条件抽出（filtering）入門｜AND/OR・query関数・複数条件の指定方法</a><br/>
条件抽出全体、AND/OR、<code>query()</code> を整理したいときにおすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-loc-iloc/">Pandas locとilocの違い｜行・列の抽出/スライス/条件指定を図解で解説</a><br/>
行・列の指定方法や、条件指定との関係を整理したいときに役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-isin/">pandas isinの使い方と仕組み｜リスト・複数条件・not isin・処理速度まで徹底解説</a><br/>
候補リストに含まれる行を抽出したいときに参考になります。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-str-contains/">pandas str.contains()の使い方｜文字列を含む行を抽出・na=Falseも解説</a><br/>
文字列を含む行を抽出したいときに使います。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-to-numeric/">pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</a><br/>
文字列の数字を数値に直してから範囲抽出したいときにおすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換とformat・NaT対処を初心者向けに解説</a><br/>
日付の範囲抽出をする前に、日付型への変換を確認したいときに役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</a><br/>
日付を抽出したあと、年・月・曜日を取り出して集計したいときにおすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-cut/">pandas cut()の使い方｜bins・labelsで数値を区間分けする方法を解説</a><br/>
範囲で抽出するのではなく、価格帯や年代などに分類したいときに使います。</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-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>
</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="toc20"> カテゴリから探す</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>

</div>


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

<p><code>between()</code> は、指定した列の値が下限から上限の範囲に入っているかを判定するメソッドです。<br />たとえば、<code>df["売上"].between(1000, 5000)</code> と書くと、<code>売上</code> が1000以上5000以下の行を判定できます。その結果を <code>df[...]</code> に入れると、範囲内の行だけを抽出できます。</p>

</div>
</div>
<div id="faq-question-1778339669209" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc22">between()は境界値を含みますか？</span></h3>
<div class="rank-math-answer ">

<p>初期設定では、境界値を含みます。<br />つまり、<code>between(1000, 5000)</code> の場合、1000ちょうど、5000ちょうどの値も含まれます。境界値を含めたくない場合は、<code>inclusive="neither"</code> を使います。</p>

</div>
</div>
<div id="faq-question-1778339682929" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc23">between()で日付の範囲抽出はできますか？</span></h3>
<div class="rank-math-answer ">

<p>できます。<br />ただし、日付列が文字列のままだと期待どおりに扱えないことがあります。日付の範囲抽出をする前に、<code>pd.to_datetime()</code> で日付型に変換してから <code>between()</code> を使うのがおすすめです。</p>

</div>
</div>
<div id="faq-question-1778339696641" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc24">between()と&gt;=・&lt;=は何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p>どちらも範囲抽出に使えます。<br /><code>between()</code> は、1つの列を下限〜上限で絞るときに短く読みやすく書けます。<br />一方、<code>&gt;=</code> や <code>&lt;=</code> は、片側だけの条件や複数条件を細かく組み合わせたいときに便利です。</p>

</div>
</div>
<div id="faq-question-1778339707569" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc25">between()とquery()はどちらを使えばよいですか？</span></h3>
<div class="rank-math-answer ">

<p>1つの列を単純に範囲で絞るなら、まずは <code>between()</code> がわかりやすいです。<br />複数条件を文章に近い形で書きたい場合は、<code>query()</code> も便利です。ただし、<code>query()</code> は列名や文字列条件の書き方に少し慣れが必要です。</p>

</div>
</div>
<div id="faq-question-1778339724225" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">between()とcut()は何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>between()</code> は、範囲に入る行を抽出するために使います。<br />一方、<code>cut()</code> は、数値を「低価格・中価格・高価格」や「20代・30代・40代」のような区間カテゴリに分けるために使います。抽出したいなら <code>between()</code>、分類したいなら <code>cut()</code> と考えるとわかりやすいです。</p>

</div>
</div>
<div id="faq-question-1778339738465" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">範囲抽出で欠損値があるとき、between()はどうなりますか？</span></h3>
<div class="rank-math-answer ">

<p><code>NaN</code> や <code>NaT</code> は、範囲内として扱われません。<br />たとえば、売上が欠損している行や、日付が変換できず <code>NaT</code> になった行は、<code>between()</code> の判定では <code>False</code> になります。</p>

</div>
</div>
<div id="faq-question-1778339757137" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">文字列の数字にbetween()を使ってもよいですか？</span></h3>
<div class="rank-math-answer ">

<p>数値として範囲抽出したい場合は、文字列のまま使わないほうが安全です。<br />CSVから読み込んだデータでは、数字に見えても文字列になっていることがあります。<code>pd.to_numeric()</code> で数値型に変換してから <code>between()</code> を使うと、意図した範囲抽出になりやすいです。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-between/">pandas between()の使い方｜数値・日付を範囲で抽出する方法</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-between/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas select_dtypes()の使い方｜データ型で列を選ぶ方法を初心者向けに解説</title>
		<link>https://pythondatalab.com/pandas-select-dtypes/</link>
					<comments>https://pythondatalab.com/pandas-select-dtypes/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 09 May 2026 08:16:35 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2064</guid>

					<description><![CDATA[<p>pandasのselect_dtypes()を使って、数値列・文字列列・日付列などをデータ型で選ぶ方法を初心者向けに解説します。dtypesで型を確認し、to_numeric()やto_datetime()で型を整えてから、必要な列だけを抽出する流れまでわかります。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-select-dtypes/">pandas select_dtypes()の使い方｜データ型で列を選ぶ方法を初心者向けに解説</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 .wp-block-table {
    margin: 0.8em 0;
    width: auto;
    border-collapse: collapse;
  }
  .colab-article .wp-block-table th,
  .colab-article .wp-block-table td {
    border: 1px solid #ddd;
  }
  .colab-article .colab-output {
    margin: 0 !important;
    padding: 1em;
    overflow-x: auto;
    background: #f7f7f7;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>


<p>CSVやExcelを読み込むと、DataFrameにはいろいろな種類の列が混ざっていることがあります。</p>
<p>たとえば、次のような列です。</p>
<ul>
<li><code>商品名</code> や <code>地域</code> のような文字列の列</li>
<li><code>売上</code> や <code>数量</code> のような数値の列</li>
<li><code>注文日</code> のような日付の列</li>
<li><code>キャンペーン対象</code> のような <code>True</code> / <code>False</code> の列</li>
</ul>
<p>このようなデータでは、列の種類によって次に行う処理が変わります。</p>
<p>数値列は平均・合計・統計量の確認に使いやすく、文字列やカテゴリ列は件数集計に使いやすく、日付列は月別・曜日別の分析に使いやすいです。</p>
<p>つまり、<strong>データ型ごとに列を分けておくと、その後の確認・集計・分析に進みやすくなります。</strong></p>
<p>そこで便利なのが、Pandasの <code>select_dtypes()</code> です。</p>
<p><code>select_dtypes()</code> を使うと、列名ではなく <strong>データ型</strong> を基準にして、数値列・文字列が入っている列・日付列などをまとめて選べます。</p>
<p>たとえば、数値列だけを選びたい場合は、次のように書きます。</p>
<pre class="line-numbers"><code class="language-python">df.select_dtypes(include="number")
</code></pre>
<p>この記事では、<code>pandas select_dtypes</code> の基本を、Google Colabでそのまま試せるサンプルデータを使って解説します。</p>


<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を学びます。</p>
<ul>
<li><code>select_dtypes()</code> でできること</li>
<li>データ型ごとに列を分けるメリット</li>
<li><code>dtypes</code> や <code>info()</code> で型を確認してから列を選ぶ流れ</li>
<li>数値列だけを選ぶ方法</li>
<li>文字列が入っている列だけを選ぶ方法</li>
<li>日付列だけを選ぶ方法</li>
<li><code>category</code> 型や <code>bool</code> 型も選べること</li>
<li><code>exclude</code> で特定の型を除外する方法</li>
</ul>
<p>この記事のゴールは、<code>select_dtypes()</code> を使って、DataFrameから数値列・文字列が入っている列・日付列をデータ型ごとに選び、その後の確認・集計・分析に進みやすくすることです。</p>


<h2><span id="toc2">まずdtypesで型を確認してからselect_dtypes()を使う</span></h2>
<p><code>select_dtypes()</code> は、Pandasの前処理で <strong>型を確認したあと</strong> に使うと便利です。</p>
<p>いきなり <code>select_dtypes()</code> を使うのではなく、まず <code>df.dtypes</code> や <code>df.info()</code> で、各列がPandas上でどのデータ型として扱われているかを確認します。</p>
<p><code>df.dtypes</code> は、列ごとのデータ型だけを簡単に確認したいときに使います。<br/>
一方、<code>df.info()</code> では、データ型に加えて、行数・欠損していない値の数・メモリ使用量などもまとめて確認できます。</p>
<p>たとえば、次のような流れです。</p>
<ol>
<li>CSVやExcelを読み込む</li>
<li><code>head()</code> でデータの中身を確認する</li>
<li><code>df.dtypes</code> や <code>df.info()</code> で列ごとのデータ型を確認する</li>
<li>数字や日付に見える列が、Pandas上でどの型として扱われているか確認する</li>
<li>必要に応じて <code>to_numeric()</code>、<code>to_datetime()</code>、<code>astype()</code> で型を整える</li>
<li><code>select_dtypes()</code> で、数値列・文字列が入っている列・日付列などをまとめて選ぶ</li>
</ol>
<p>この流れにすると、「見た目は数字でも、Pandas上では文字列として扱われている」「日付に見えても、まだ日付型ではない」といった状態に気づきやすくなります。</p>
<p>上で確認したように、<code>select_dtypes()</code> のメリットは、データ型ごとに列を分けられることです。</p>
<p>数値列、文字列が入っている列、日付列では、次に行う処理が異なります。<br/>
そのため、先に <code>select_dtypes()</code> で列を種類ごとに整理しておくと、確認・集計・分析へ進みやすくなります。</p>
<p>ただし、型が違う列を混ぜたまま、同じ方法で集計・可視化できるわけではありません。<br/>
数値列なら統計量の確認、文字列やカテゴリ列なら件数集計、日付列なら月別・曜日別の分析のように、列の種類に合った処理を選ぶことが大切です。</p>
<p>この流れで出てくる基本操作が不安な場合は、以下の記事も参考になります。<code>dtypes</code> や <code>info()</code> による型の確認方法は、info()・describe()の記事で解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a></li>
<li><a href="https://pythondatalab.com/pandas-head/">pandas head()の使い方｜先頭行を確認してデータの中身を把握する方法</a></li>
<li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
<li><a href="https://pythondatalab.com/pandas-to-numeric/">pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</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-astype/">pandas astype()の使い方｜文字列・数値への型変換とエラー対処を初心者向けに解説</a></li>
</ul>


<h2><span id="toc3">select_dtypes()とは？</span></h2>
<p><code>select_dtypes()</code> は、DataFrameの列を <strong>データ型（dtype）で選ぶ</strong> メソッドです。</p>
<p><code>dtype</code> は、Pandasで使われる「データ型」を表す言葉です。この記事では、基本的には「データ型」として説明します。</p>
<p>基本形は次のとおりです。</p>
<pre class="line-numbers"><code class="language-python">df.select_dtypes(include=選びたい型)
</code></pre>
<p>または、特定の型を除外したい場合は次のように書きます。</p>
<pre class="line-numbers"><code class="language-python">df.select_dtypes(exclude=除外したい型)
</code></pre>
<p>まず、初心者が最初に覚えるなら、次の3つで十分です。</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; border: 1px solid #ddd;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">書き方の例</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う場面</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>df.select_dtypes(include="number")</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>df.select_dtypes(include=["object", "string"])</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>df.select_dtypes(include="datetime")</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">月別・曜日別の分析の前</td>
</tr>
</tbody>
</table>
<p>ポイントは、<code>select_dtypes()</code> は <strong>型を変換するメソッドではない</strong> ということです。</p>
<p>見た目が数字や日付のように見えても、Pandas上のデータ型が違うと、期待した列として選ばれないことがあります。<br/>
そのため、<code>select_dtypes()</code> を使う前後では、<code>df.dtypes</code> や<code>df.info()</code>でデータ型を確認することが大切です。</p>


<h2><span id="toc4">まずはサンプルデータを作る</span></h2>
<p>今回は、ネットショップの注文データをイメージしたDataFrameを使います。</p>
<p>このデータには、数値・文字列・日付・真偽値が混ざっています。<br/>
実際のCSVやExcelデータでも、このようにいろいろな型の列が混ざっていることがよくあります。</p>


<pre class="line-numbers"><code class="language-python">
import pandas as pd
raw_df = pd.DataFrame({
    &quot;注文ID&quot;: [1001, 1002, 1003, 1004, 1005],
    &quot;商品名&quot;: [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;, &quot;モニター&quot;, &quot;USBメモリ&quot;],
    &quot;地域&quot;: [&quot;東京&quot;, &quot;大阪&quot;, &quot;東京&quot;, &quot;福岡&quot;, &quot;大阪&quot;],
    &quot;売上&quot;: [&quot;120000&quot;, &quot;3000&quot;, &quot;8000&quot;, &quot;35000&quot;, &quot;不明&quot;],
    &quot;数量&quot;: [1, 2, 1, 1, 3],
    &quot;割引率&quot;: [0.10, 0.00, 0.05, 0.15, 0.00],
    &quot;注文日&quot;: [&quot;2026-05-01&quot;, &quot;2026-05-02&quot;, &quot;2026-05-03&quot;, &quot;2026-05-04&quot;, &quot;2026-05-05&quot;],
    &quot;キャンペーン対象&quot;: [True, False, True, True, False],
    &quot;メモ&quot;: [&quot;初回購入&quot;, &quot;リピート&quot;, &quot;法人&quot;, &quot;初回購入&quot;, &quot;リピート&quot;]
})

raw_df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">地域</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">割引率</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">キャンペーン対象</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">メモ</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;">1001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">1002</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;">3000</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;">0.00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">1003</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;">8000</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;">0.05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1004</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;">35000</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;">0.15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-04</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1005</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">0.00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">リピート</td>
</tr>
</tbody>
</table>

<p>上のデータでは、<code>売上</code> は数字のように見えます。<br/>
しかし、最後に <code>"不明"</code> という文字が入っているため、この時点では数値列として扱えない可能性があります。</p>
<p>まずは、<code>dtypes</code> で列ごとの型を確認してみましょう。</p>


<pre class="line-numbers"><code class="language-python">
raw_df.dtypes
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">dtype</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">int64</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;">object</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;">object</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;">object</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;">int64</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;">float64</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;">object</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;">bool</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;">object</td>
</tr>
</tbody>
</table>

<p><code>dtypes</code> を見ると、列ごとのデータ型を確認できます。<br/>
同じように、<code>info()</code> でも各列のデータ型は <code>Dtype</code> として確認できます。</p>
<p>ここで大切なのは、<strong>見た目が数字かどうかではなく、Pandasがどの型として認識しているか</strong> です。</p>
<p>たとえば、<code>売上</code> は数字に見えますが、<code>"不明"</code> が混ざっているため、数値ではなく <code>object</code> 型として扱われています。</p>
<p>では、この状態で数値列だけを選ぶとどうなるか確認してみましょう。</p>


<h2><span id="toc5">まずは変換前のデータで数値列だけを選んでみる</span></h2>
<p>数値列だけを選びたい場合は、<code>include="number"</code> を指定します。</p>
<p>まずは、型を変換する前の <code>raw_df</code> で数値列だけを選んでみます。</p>


<pre class="line-numbers"><code class="language-python">
raw_df.select_dtypes(include=&quot;number&quot;)
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">割引率</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;">1001</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;">0.10</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;">1002</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;">0.00</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;">1003</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;">0.05</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;">1004</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;">0.15</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;">1005</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;">0.00</td>
</tr>
</tbody>
</table>

<p>実行結果を見ると、<code>注文ID</code>、<code>数量</code>、<code>割引率</code> は選ばれますが、<code>売上</code> は含まれていません。</p>
<p>理由は、<code>売上</code> がPandas上では数値型ではなく <code>object</code> 型として扱われているためです。<br/>
このように、数字に見える列でも、データ型が文字列系のままだと <code>include="number"</code> では選ばれません。</p>
<p><code>売上</code> を数値列として扱いたい場合は、先に <code>to_numeric()</code> で数値型に変換します。</p>


<h2><span id="toc6">売上を数値型に変換する</span></h2>
<p>ここでは、<code>売上</code> を数値列として扱えるようにします。</p>
<p><code>売上</code> には <code>"不明"</code> が混ざっているため、そのままでは数値型にできません。<br/>
そこで、<code>pd.to_numeric()</code> の <code>errors="coerce"</code> を使い、数値に変換できない値を <code>NaN</code> にします。</p>
<p>数値変換の詳しい使い方は、以下の記事で解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-to-numeric/">pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</a></li>
</ul>


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

df[&quot;売上&quot;] = pd.to_numeric(df[&quot;売上&quot;], errors=&quot;coerce&quot;)

df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">地域</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">割引率</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">キャンペーン対象</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">メモ</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;">1001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">ノートPC</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.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;">0.10</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">1002</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;">3000.0</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;">0.00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">1003</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;">8000.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;">0.05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1004</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;">35000.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;">0.15</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-04</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1005</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">NaN</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;">0.00</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">リピート</td>
</tr>
</tbody>
</table>

<p><code>売上</code> の <code>"不明"</code> は、<code>errors="coerce"</code> によって <code>NaN</code> になりました。<br/>
これは「数値に変換できない値を欠損値として扱う」という意味です。</p>
<p>今回は学習用の例として <code>"不明"</code> を <code>NaN</code> に変換しています。<br/>
実務では、<code>"不明"</code> が本当に欠損値として扱ってよい値なのかを確認してから処理しましょう。</p>
<p>次に、型がどう変わったか確認します。</p>


<pre class="line-numbers"><code class="language-python">
df.dtypes
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">dtype</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">int64</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;">object</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;">object</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;">float64</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;">int64</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;">float64</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;">object</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;">bool</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;">object</td>
</tr>
</tbody>
</table>

<p>これで、<code>売上</code> は数値型として扱えるようになりました。</p>
<p>もう一度、<code>select_dtypes(include="number")</code> で数値列だけを選んでみましょう。</p>


<h2><span id="toc7">変換後に数値列だけを選ぶ：include=&#8221;number&#8221;</span></h2>
<p><code>売上</code> を数値型に変換したあとであれば、<code>include="number"</code> で数値列として選ばれるようになります。</p>


<pre class="line-numbers"><code class="language-python">
numeric_df = df.select_dtypes(include=&quot;number&quot;)
numeric_df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">割引率</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;">1001</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.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;">0.10</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;">1002</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</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;">0.00</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;">1003</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">8000.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;">0.05</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;">1004</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">35000.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;">0.15</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;">1005</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</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;">0.00</td>
</tr>
</tbody>
</table>

<p>この結果では、<code>注文ID</code>、<code>売上</code>、<code>数量</code>、<code>割引率</code> のような数値型の列だけが残ります。</p>
<p>一方で、<code>商品名</code>、<code>地域</code>、<code>注文日</code>、<code>メモ</code> などは数値型ではないため、この結果には含まれません。<br/>
また、<code>キャンペーン対象</code> のような <code>True</code> / <code>False</code> の列はbool型として扱われるため、ここでは数値列とは分けて考えるとわかりやすいです。</p>
<p>ただし、<code>注文ID</code> のようなID列も数値型なので、<code>include="number"</code> で選ばれます。<br/>
ここは初心者が特に注意したいポイントです。</p>
<p><strong>数値型の列として選ばれること</strong> と、<strong>平均・合計などの分析対象として意味があること</strong> は同じではありません。<br/>
たとえば、<code>注文ID</code> は数値型ですが、平均値や合計を出しても分析上の意味は薄いです。</p>
<p>そのため、<code>include="number"</code> で数値列をまとめて選んだあとでも、ID列のように分析対象にしない列は、目的に応じて除外しましょう。</p>


<pre class="line-numbers"><code class="language-python">
numeric_df.describe()
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文ID</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">割引率</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">count</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">mean</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1003.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">41500.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.600000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.060000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">std</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.581139</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">54187.944539</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.894427</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.065192</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">min</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1001.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">25%</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1002.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">6750.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">50%</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1003.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">21500.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.050000</td>
</tr>
<tr>
<td style="min-width: 3em; 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;">1004.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">56250.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.100000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">max</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1005.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">120000.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">0.150000</td>
</tr>
</tbody>
</table>

<p><code>describe()</code> を使うと、数値列の件数、平均、最小値、最大値などを確認できます。</p>
<p>より詳しく <code>describe()</code> の見方を確認したい場合は、以下の記事も参考になります。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
</ul>


<h2><span id="toc8">文字列が入っている列だけを選ぶ：include=[&#8220;object&#8221;, &#8220;string&#8221;]</span></h2>
<p>文字列が入っている列だけを選びたい場合は、<code>include=["object", "string"]</code> のように指定します。</p>
<p>Pandasでは、文字列が <code>object</code> 型として扱われることもあれば、<code>string</code> 型として扱われることもあります。<br/>
初心者のうちは、厳密な違いまで深入りしすぎず、まずは <strong>文字列っぽい列を選ぶときは object と string を意識する</strong> と覚えておくとよいです。</p>
<p>なお、pandasのバージョンによって、文字列が入っている列のデータ型の表示や選び方が少し変わる場合があります。<br/>
うまく選べないときは、まず <code>df.dtypes</code> で実際のデータ型を確認してください。</p>


<pre class="line-numbers"><code class="language-python">
text_df = df.select_dtypes(include=[&quot;object&quot;, &quot;string&quot;])
text_df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">地域</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">メモ</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;">ノートPC</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;">2026-05-01</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;">マウス</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;">2026-05-02</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;">キーボード</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;">2026-05-03</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;">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;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-04</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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">2026-05-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">リピート</td>
</tr>
</tbody>
</table>

<p>この例では、<code>商品名</code>、<code>地域</code>、<code>注文日</code>、<code>メモ</code> などが選ばれます。</p>
<p>ここで <code>注文日</code> も選ばれるのは、まだ <code>to_datetime()</code> で日付型に変換していないためです。<br/>
見た目が日付でも、Pandas上で文字列として扱われていれば、文字列系の列として選ばれます。</p>
<p>文字列が入っている列だけを取り出すと、<code>value_counts()</code> で種類ごとの件数を確認しやすくなります。</p>


<h2><span id="toc9">object型を選ぶときの注意</span></h2>
<p>文字列が入っている列を選びたいときは、次のように書けます。</p>
<pre class="line-numbers"><code class="language-python">df.select_dtypes(include=["object", "string"])
</code></pre>
<p>ただし、<code>object</code> 型は「文字列専用の型」ではありません。</p>
<p>CSVやExcelを読み込んだデータでは、商品名・地域名・メモのような文字列列が <code>object</code> 型になることが多いです。<br/>
しかし、<code>object</code> 型には、文字列だけでなく、リストや辞書などのPythonオブジェクトが入ることもあります。</p>
<p>そのため、文字列列だけを正確に扱いたい場合は、まず <code>df.dtypes</code> で型を確認し、必要に応じて <code>astype("string")</code> で文字列型に整えてから使うと安心です。</p>
<pre class="line-numbers"><code class="language-python">df["商品名"] = df["商品名"].astype("string")
</code></pre>
<p><code>select_dtypes()</code> は便利ですが、最初に <code>df.dtypes</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 style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">count</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;">2</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>
</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>
</tr>
</tbody>
</table>

<p><code>value_counts()</code> は、カテゴリ名や文字列の出現回数を数えるときに便利です。</p>
<p>たとえば、地域別、商品名別、メモの種類別などを確認したいときに使えます。</p>
<p>詳しくは、以下の記事で解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
</ul>


<h2><span id="toc10">日付列だけを選ぶ：include=&#8221;datetime&#8221;</span></h2>
<p>日付列だけを選びたい場合は、<code>include="datetime"</code> を指定します。</p>
<p>ただし、見た目が日付の文字列でも、Pandas上で日付型になっていなければ選ばれません。<br/>
今回の <code>注文日</code> も、ここまでは文字列のままです。</p>
<p>そのため、日付列として選ぶ前に、<code>to_datetime()</code> で日付型に変換します。<br/>
<code>to_datetime()</code> の詳しい使い方は、以下の記事で解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換と format・NaT 対処を初心者向けに解説</a></li>
</ul>


<pre class="line-numbers"><code class="language-python">
df[&quot;注文日&quot;] = pd.to_datetime(df[&quot;注文日&quot;])

date_df = df.select_dtypes(include=&quot;datetime&quot;)
date_df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</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;">2026-05-01</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;">2026-05-02</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;">2026-05-03</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;">2026-05-04</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;">2026-05-05</td>
</tr>
</tbody>
</table>

<p>日付列を選べるようになると、月別集計や曜日別集計などに進みやすくなります。</p>
<p>なお、日付列から年・月・曜日を取り出す方法は、以下の記事で詳しく解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</a></li>
</ul>


<h2><span id="toc11">補足：category列やbool列も選べる</span></h2>
<p><code>select_dtypes()</code> では、数値列・文字列が入っている列・日付列だけでなく、カテゴリ型や真偽値型の列も選べます。</p>
<p>たとえば、カテゴリ型の列を選ぶ場合は <code>include="category"</code>、<code>True</code> / <code>False</code> のような真偽値列を選ぶ場合は <code>include="bool"</code> を使います。</p>
<p>ただし、初心者のうちは、まず <code>include="number"</code>、<code>include=["object", "string"]</code>、<code>include="datetime"</code> の3つを優先して覚えれば十分です。<br/>
<code>category</code> や <code>bool</code> は、必要になったときに補足として使うくらいで問題ありません。</p>
<p><code>category</code> 型への変換は <code>astype("category")</code> で行えますが、詳しい型変換は以下の記事で解説しています。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方｜文字列・数値への型変換とエラー対処を初心者向けに解説</a></li>
</ul>


<h2><span id="toc12">excludeで特定の型を除外する</span></h2>
<p><code>include</code> は「この型を選ぶ」という指定です。<br/>
一方で、<code>exclude</code> は「この型を除外する」という指定です。</p>
<p>たとえば、数値列以外を選びたい場合は、次のように書けます。</p>


<pre class="line-numbers"><code class="language-python">
non_numeric_df = df.select_dtypes(exclude=&quot;number&quot;)
non_numeric_df
</code></pre>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品名</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">地域</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注文日</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">キャンペーン対象</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">メモ</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;">ノートPC</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;">2026-05-01</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">マウス</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;">2026-05-02</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</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;">キーボード</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;">2026-05-03</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">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;">福岡</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2026-05-04</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">True</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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">USBメモリ</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;">2026-05-05</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">False</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">リピート</td>
</tr>
</tbody>
</table>

<p><code>exclude="number"</code> を指定すると、数値型の列が除外されます。</p>
<p>ただし、初心者のうちは、まず <code>include</code> を中心に使うのがおすすめです。<br/>
<code>exclude</code> は、慣れてきてから「数値列以外をまとめて確認したい」ときに使うとよいでしょう。</p>


<h2><span id="toc13">select_dtypes()で次の処理に進みやすくする</span></h2>
<p><code>select_dtypes()</code> で列をデータ型ごとに分けておくと、その後の処理に進みやすくなります。</p>
<p>たとえば、数値列は統計量の確認、文字列やカテゴリ列は件数集計、日付列は日付を使った分析に向いています。<br/>
この記事では詳しい集計や可視化には深入りせず、「分析に使う列をデータ型ごとに整理する」ところまでを押さえます。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
<li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
<li><a href="https://pythondatalab.com/matplotlib-hist-boxplot/">Matplotlib ヒストグラム＆箱ひげ図 入門｜bins設定と外れ値の可視化・分析</a></li>
</ul>


<h2><span id="toc14">まとめ</span></h2>
<p>この記事では、<code>pandas select_dtypes</code> の使い方を解説しました。</p>
<p><code>select_dtypes()</code> は、DataFrameの中から <strong>データ型を基準に列を選ぶ</strong> メソッドです。</p>
<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; border: 1px solid #ddd;">やりたいこと</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">書き方</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>df.select_dtypes(include="number")</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>df.select_dtypes(include=["object", "string"])</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>df.select_dtypes(include="datetime")</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>df.select_dtypes(include="bool")</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>df.select_dtypes(exclude="number")</code></td>
</tr>
</tbody>
</table>
<p><code>category</code> 型の列を選びたい場合は、<code>include="category"</code> も使えます。<br/>
ただし、初心者のうちは、まず数値列・文字列が入っている列・日付列を選べれば十分です。</p>
<p>注意したいのは、<code>select_dtypes()</code> は <strong>型を変換するメソッドではない</strong> という点です。<br/>
数字に見える列や日付に見える列でも、Pandas上のデータ型が違えば選ばれないことがあります。</p>
<p>うまく選べないときは、まず <code>df.dtypes</code> や <code>df.info()</code> で型を確認しましょう。</p>
<p>必要に応じて、数値なら <code>to_numeric()</code>、日付なら <code>to_datetime()</code>、文字列型やカテゴリ型への変換なら <code>astype()</code> で型を整えてから、<code>select_dtypes()</code> を使います。</p>
<p>データ型を確認し、必要に応じて型を整えたうえで <code>select_dtypes()</code> を使うと、列の種類に合った次の処理へ進みやすくなります。</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> <div class="related-box"> <h3><span id="toc15"> カテゴリから探す</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-1778312073060" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc16">pandasで数値列だけ抽出するにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>数値列だけ抽出したい場合は、次のように書きます。<br /><code>df.select_dtypes(include="number")</code></p>
<p>数字に見える列でも <code>object</code> 型になっている場合は選ばれないため、必要に応じて <code>to_numeric()</code> で数値型に変換します。</p>

</div>
</div>
<div id="faq-question-1778312089484" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc17">pandasで文字列が入っている列だけ選ぶにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>文字列が入っている列だけを選びたい場合は、次のように書きます。<br /><code>df.select_dtypes(include=["object", "string"])</code></p>
<p>うまく選べないときは、まず <code>df.dtypes</code> で実際のデータ型を確認しましょう。</p>

</div>
</div>
<div id="faq-question-1778312104029" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc18">日付列だけを選ぶことはできますか？</span></h3>
<div class="rank-math-answer ">

<p>できます。日付型の列だけを選ぶ場合は、次のように書きます。<br /><code>df.select_dtypes(include="datetime")</code></p>
<p>見た目が日付でも文字列のままでは選ばれないため、必要に応じて <code>to_datetime()</code> で日付型に変換します。</p>

</div>
</div>
<div id="faq-question-1778312119405" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc19">select_dtypes()で型は変換できますか？</span></h3>
<div class="rank-math-answer ">

<p>できません。<br /><code>select_dtypes()</code> は、データ型を基準に列を選ぶメソッドです。<br />型を変換したい場合は、<code>to_numeric()</code>、<code>to_datetime()</code>、<code>astype()</code> などを使います。</p>

</div>
</div>
<div id="faq-question-1778312140181" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc20">うまく列が選ばれないときは何を確認すればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>まずは、<code>df.dtypes</code> または <code>df.info()</code> でPandas上のデータ型を確認しましょう。<br />数字に見える列が <code>object</code> 型のままだと <code>include="number"</code> では選ばれません。<br />日付に見える列が文字列型のままだと <code>include="datetime"</code> では選ばれません。</p>

</div>
</div>
<div id="faq-question-1778312166309" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc21">includeとexcludeを同時に使うときの注意はありますか？</span></h3>
<div class="rank-math-answer ">

<p><code>include</code> と <code>exclude</code> は同時に使えます。<br />たとえば、数値列を選びつつ、整数型だけを除外したい場合は次のように書けます。<br /><code>df.select_dtypes(include="number", exclude="int64")</code></p>
<p>ただし、<code>include</code> と <code>exclude</code> に同じ型を指定するとエラーになります。<br /><code>df.select_dtypes(include="number", exclude="number")</code></p>
<p>初心者のうちは、まず <code>include</code> だけで必要な型を選ぶ使い方から覚えるのがおすすめです。<br />慣れてきたら、不要な型を外したい場面で <code>exclude</code> を使うとよいでしょう。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-select-dtypes/">pandas select_dtypes()の使い方｜データ型で列を選ぶ方法を初心者向けに解説</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-select-dtypes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas where()・mask()の使い方｜条件に応じて値を残す・置き換える方法</title>
		<link>https://pythondatalab.com/pandas-where-mask/</link>
					<comments>https://pythondatalab.com/pandas-where-mask/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Wed, 06 May 2026 13:48:04 +0000</pubDate>
				<category><![CDATA[Python実行環境・設定]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2060</guid>

					<description><![CDATA[<p>pandasのwhere()・mask()の使い方を初心者向けに解説。条件を満たす値を残す方法、条件に合う値を置き換える方法、where()とmask()の違い、replace()・fillna()・loc・np.where()との使い分けも整理します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-where-mask/">pandas where()・mask()の使い方｜条件に応じて値を残す・置き換える方法</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 href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css" rel="stylesheet"/>
<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;
    background: #2d2d2d;
    color: #ccc;
    overflow-x: auto;
  }
  .colab-article .wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 0.8em 0;
    display: table;
  }
  .colab-article .wp-block-table th,
  .colab-article .wp-block-table td {
    border: 1px solid #ddd;
    vertical-align: top;
  }
  .colab-article .colab-output {
    margin: 0 !important;
    padding: 0.8em;
    white-space: pre-wrap;
    background: #f6f8fa;
    border: 1px solid #ddd;
    overflow-x: auto;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }

  .colab-article pre.line-numbers,
  .colab-article pre[class*="language-"] {
    margin-top: 0 !important;
    margin-bottom: 0 !important;
  }
  .colab-article code.language-python {
    white-space: pre;
  }

</style>

<p>Pandasで前処理をしていると、次のような場面で迷うことがあります。</p>
<ul>
<li>60点以上の点数だけ残し、60点未満は欠損値として扱いたい</li>
<li>売上がマイナスになっている不自然な値だけ、0やNaNにしたい</li>
<li>年齢が120歳を超えるような確認が必要な値だけ、欠損値にしたい</li>
<li><code>replace()</code>、<code>loc</code>、<code>where()</code>、<code>mask()</code>のどれを使えばよいかわからない</li>
</ul>
<p>最初に結論を言うと、<strong><code>where()</code>は「条件を満たす値を残す」ために使い、<code>mask()</code>は「条件を満たす値を置き換える」ために使います。</strong></p>
<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;"><code>where()</code></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;"><code>mask()</code></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;"><code>replace()</code></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;"><code>fillna()</code></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;">条件抽出・<code>loc</code></td>
</tr>
</tbody>
</table>
<p>この記事では、Google Colabでそのまま試せる小さなDataFrameを使いながら、<code>where()</code>と<code>mask()</code>の違い、使いどころ、よくあるミスを初心者向けに整理します。</p>
<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を学びます。</p>
<ul>
<li><code>where()</code>の基本的な使い方</li>
<li><code>mask()</code>の基本的な使い方</li>
<li><code>where()</code>と<code>mask()</code>の違い</li>
<li>条件に合わない値を<code>NaN</code>にする方法</li>
<li><code>NaN</code>にしたときに整数列が小数表示になる理由</li>
<li>条件に応じて別の値に置き換える方法</li>
<li><code>loc</code>、<code>replace()</code>、<code>fillna()</code>、<code>np.where()</code>との使い分け</li>
<li>初心者が間違えやすい条件式の向き</li>
</ul>
<h2><span id="toc2">Pandas前処理の中での位置づけ</span></h2>
<p><code>where()</code>と<code>mask()</code>は、DataFrameを確認したあとに、<strong>条件に応じて値を整える前処理</strong>で役立ちます。</p>
<p>たとえば、次のような流れです。</p>
<ol>
<li><code>info()</code>や<code>describe()</code>でデータの型・欠損値・統計量を確認する</li>
<li><code>unique()</code>や<code>value_counts()</code>で値の中身を確認する</li>
<li><code>replace()</code>で表記ゆれを直す</li>
<li><code>where()</code>や<code>mask()</code>で条件に合わない値・確認が必要な値を整理する</li>
<li><code>fillna()</code>で欠損値を補う</li>
<li><code>groupby()</code>やグラフで集計・可視化する</li>
</ol>
<p>つまり、<code>where()</code>と<code>mask()</code>は、<strong>集計や可視化の前に、条件に応じて値を整えるための道具</strong>です。</p>
<h2><span id="toc3">where()とmask()の判断基準</span></h2>
<p>まず、<code>where()</code>と<code>mask()</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;"><code>where(条件)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件を満たす値を残す</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上だけ残す</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>mask(条件)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件を満たす値を置き換える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点未満をNaNにする</td>
</tr>
</tbody>
</table>
<p>特に初心者が混乱しやすいのは、<strong>条件に合う値をどうしたいのか</strong>です。</p>
<ul>
<li>条件に合う値を残したい → <code>where()</code></li>
<li>条件に合う値を消したい・置き換えたい → <code>mask()</code></li>
</ul>
<p>この記事では、まず同じサンプルデータを使って、<code>where()</code>と<code>mask()</code>の動きを確認していきます。</p>
<h2><span id="toc4">サンプルデータを用意する</span></h2>
<p>ここでは、テスト点数、売上、年齢を持つ小さなDataFrameを使います。</p>
<p>売上の<code>-500</code>は、今回の例では「本来はマイナスにならないはずの入力ミス」として扱います。<br/>
年齢の<code>135</code>も、今回の例では「確認が必要な値」として扱います。</p>
<pre class="line-numbers"><code class="language-python">import pandas as pd

df = pd.DataFrame({
    "名前": ["田中", "佐藤", "鈴木", "高橋", "伊藤", "山本"],
    "点数": [82, 55, 91, 47, 60, 73],
    "売上": [12000, -500, 18500, 0, 9200, 15000],
    "年齢": [24, 31, 135, 28, 42, 19]
})

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></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;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">24</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">-500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">31</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">18500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">135</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">28</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">9200</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">42</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">15000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">19</td></tr></tbody></table>
<p>このDataFrameでは、次のような前処理を考えます。</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;">点数</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上だけ残したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点未満を<code>NaN</code>にする</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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">負の値を0または<code>NaN</code>にする</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;">120歳を超える値を確認対象にしたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120歳超を<code>NaN</code>にする</td>
</tr>
</tbody>
</table>
<p>実務でも、CSVやExcelを読み込んだあとに、このような「条件に応じた値の整理」が必要になることがあります。</p>
<h2><span id="toc5">where()の基本：条件を満たす値を残す</span></h2>
<p><code>where()</code>は、<strong>条件を満たす値を残し、条件を満たさない値を置き換える</strong>メソッドです。</p>
<p>基本形は次のように考えます。</p>
<pre class="line-numbers"><code class="language-python">Series.where(条件, other=置き換える値)
</code></pre>
<p><code>other</code>を指定しない場合、条件を満たさない値は<code>NaN</code>になります。</p>
<pre class="line-numbers"><code class="language-python">Series.where(条件)
</code></pre>
<p>ここでは、点数が60点以上の値だけを残し、60点未満を<code>NaN</code>にしてみます。</p>
<pre class="line-numbers"><code class="language-python">df["点数_where"] = df["点数"].where(df["点数"] &gt;= 60)

df[["名前", "点数", "点数_where"]]</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;">点数_where</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;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">91.0</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">60.0</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">73.0</td></tr></tbody></table>
<p>上のコードでは、<code>df["点数"] &gt;= 60</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;">82</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">82</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">55</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点未満</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">91</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">91</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">47</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点未満</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">60</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">73</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">73</td>
</tr>
</tbody>
</table>
<p>ここで大切なのは、<code>where()</code>は「条件に合う値を置き換える」のではなく、<strong>条件に合う値を残す</strong>という点です。</p>
<h3><span id="toc6">補足：NaNが入ると小数表示になることがある</span></h3>
<p><code>where()</code>や<code>mask()</code>で<code>NaN</code>を作ると、整数だった列が<code>82.0</code>のように小数で表示されることがあります。</p>
<p>これは、<code>NaN</code>が欠損値を表すため、整数だけの列に<code>NaN</code>が混ざると、Pandasが列全体を小数型として扱うことがあるためです。</p>
<p>そのため、結果が<code>82.0</code>のように表示されても、処理が間違っているとは限りません。まずは、<strong>どの値が残り、どの値が<code>NaN</code>になったか</strong>を確認しましょう。</p>
<h2><span id="toc7">where()で条件に合わない値を別の値に置き換える</span></h2>
<p><code>where()</code>では、<code>other</code>を指定すると、条件を満たさない値を別の値に置き換えられます。</p>
<pre class="line-numbers"><code class="language-python">Series.where(残したい条件, other=条件に合わないときの値)
</code></pre>
<p>ここでは、売上が0以上ならそのまま残し、0未満の売上を0に置き換えます。</p>
<pre class="line-numbers"><code class="language-python">df["売上_where_0"] = df["売上"].where(df["売上"] &gt;= 0, other=0)

df[["名前", "売上", "売上_where_0"]]</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;">売上_where_0</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;">12000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">-500</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;">2</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">鈴木</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">18500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">18500</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;">0</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;">4</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">伊藤</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">9200</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">9200</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;">15000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">15000</td></tr></tbody></table>
<p>この例では、売上が0以上の値はそのまま残り、<code>-500</code>だけが<code>0</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;">12000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">-500</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>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">18500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18500</td>
</tr>
<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;">0以上</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;">9200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">9200</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">15000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">0以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15000</td>
</tr>
</tbody>
</table>
<p><code>0</code>は今回のデータでは「売上がなかった」という意味のある値として残しています。<br/>
一方、<code>-500</code>は「本来はマイナスにならない想定の売上」として、確認・修正対象にしています。</p>
<h2><span id="toc8">mask()の基本：条件を満たす値を置き換える</span></h2>
<p><code>mask()</code>は、<code>where()</code>とは逆に、<strong>条件を満たす値を置き換える</strong>メソッドです。</p>
<p>基本形は次のように考えます。</p>
<pre class="line-numbers"><code class="language-python">Series.mask(条件, other=置き換える値)
</code></pre>
<p><code>other</code>を指定しない場合、条件を満たす値は<code>NaN</code>になります。</p>
<pre class="line-numbers"><code class="language-python">Series.mask(条件)
</code></pre>
<p>ここでは、年齢が120歳を超える値を確認対象として、<code>NaN</code>にします。</p>
<pre class="line-numbers"><code class="language-python">df["年齢_mask"] = df["年齢"].mask(df["年齢"] &gt; 120)

df[["名前", "年齢", "年齢_mask"]]</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;">年齢_mask</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;">24</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">24.0</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;">31</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">31.0</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;">135</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">28</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">28.0</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;">42</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">42.0</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;">19</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">19.0</td></tr></tbody></table>
<p>この例では、<code>年齢 &gt; 120</code>という条件を満たす<code>135</code>だけが<code>NaN</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;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">31</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">135</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120超</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">28</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">28</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">19</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">19</td>
</tr>
</tbody>
</table>
<p><code>mask()</code>は、条件に合う値を隠す・置き換えるイメージで使うと理解しやすいです。</p>
<h2><span id="toc9">where()とmask()の違いを同じデータで比較する</span></h2>
<p><code>where()</code>と<code>mask()</code>は、条件の向きを逆にすると同じ結果を作れることがあります。</p>
<p>たとえば、次の2つはどちらも「60点未満をNaNにする」処理です。</p>
<ul>
<li><code>where(df["点数"] &gt;= 60)</code>：60点以上を残す</li>
<li><code>mask(df["点数"] &lt; 60)</code>：60点未満を置き換える</li>
</ul>
<p>同じデータで比較してみましょう。</p>
<pre class="line-numbers"><code class="language-python">compare = pd.DataFrame({
    "名前": df["名前"],
    "元の点数": df["点数"],
    "where_60点以上を残す": df["点数"].where(df["点数"] &gt;= 60),
    "mask_60点未満をNaN": df["点数"].mask(df["点数"] &lt; 60)
})

compare</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;">where_60点以上を残す</th><th style="white-space: nowrap; padding: 0.2em 0.4em;">mask_60点未満をNaN</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;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">91.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">91.0</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">60.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">60.0</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">73.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">73.0</td></tr></tbody></table>
<p>結果を見ると、<code>where()</code>と<code>mask()</code>で同じような結果になっています。</p>
<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>
<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>where(df["点数"] &gt;= 60)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上なら残す</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件を満たさない60点未満がNaN</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>mask(df["点数"] &lt; 60)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点未満なら置き換える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件を満たす60点未満がNaN</td>
</tr>
</tbody>
</table>
<p>迷ったときは、次のように判断してください。</p>
<ul>
<li><strong>残したい条件</strong>を書きたい → <code>where()</code></li>
<li><strong>置き換えたい条件</strong>を書きたい → <code>mask()</code></li>
</ul>
<h2><span id="toc10">複数条件でwhere()を使う場合</span></h2>
<p><code>where()</code>や<code>mask()</code>では、複数条件も指定できます。</p>
<p>複数条件を書くときは、次の点に注意します。</p>
<ul>
<li>それぞれの条件を<code>()</code>で囲む</li>
<li>AND条件は<code>&amp;</code>でつなぐ</li>
<li>OR条件は<code>|</code>でつなぐ</li>
</ul>
<p>ここでは、点数が60点以上かつ90点以下の値だけを残してみます。</p>
<pre class="line-numbers"><code class="language-python">df["点数_60から90"] = df["点数"].where((df["点数"] &gt;= 60) &amp; (df["点数"] &lt;= 90))

df[["名前", "点数", "点数_60から90"]]</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;">点数_60から90</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;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">60.0</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">73.0</td></tr></tbody></table>
<p>この例では、60点以上かつ90点以下の値だけが残ります。<br/>
<code>55</code>や<code>47</code>は60点未満なので<code>NaN</code>になり、<code>91</code>は90点を超えているため<code>NaN</code>になります。</p>
<p>複数条件は便利ですが、初心者のうちは条件式が長くなりやすいです。<br/>
まずは単一条件で<code>where()</code>と<code>mask()</code>の考え方を理解し、そのあと複数条件に進むと分かりやすくなります。</p>
<h2><span id="toc11">補足：DataFrame全体にもwhere()・mask()は使える</span></h2>
<p>ここまでの例では、<code>df["点数"]</code>のように1つの列に対して<code>where()</code>や<code>mask()</code>を使いました。</p>
<p>実は、<code>DataFrame</code>全体に対しても使えます。
ただし、初心者のうちは、まず<strong>1つの列ごとに処理する</strong>ほうが結果を確認しやすいです。</p>
<p>ここでは、数値列だけを取り出して、0以上の値を残し、0未満の値を<code>NaN</code>にしてみます。</p>
<pre class="line-numbers"><code class="language-python">numeric_df = df[["点数", "売上", "年齢"]]

numeric_df.where(numeric_df &gt;= 0)</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">24</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">31</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">18500.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">135</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">0.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">28</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">9200.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">42</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">15000.0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">19</td></tr></tbody></table>
<p>このように、<code>DataFrame.where()</code>を使うと、DataFrame内の各値に対して条件を確認できます。</p>
<p>同じ考え方で、<code>DataFrame.mask()</code>もDataFrame全体に使えます。ただし、初心者のうちは、まず1列ずつ処理して結果を確認するほうが安全です。</p>
<p>ただし、実際の記事や学習では、最初からDataFrame全体に使うよりも、</p>
<pre class="line-numbers"><code class="language-python">df["列名"].where(条件)
</code></pre>
<p>のように、<strong>対象の列を決めてから使う</strong>ほうがミスに気づきやすいです。</p>
<h2><span id="toc12">where()・mask()・replace()・fillna()・locの使い分け</span></h2>
<p><code>where()</code>や<code>mask()</code>で迷う理由は、似たような処理をするメソッドが多いからです。</p>
<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>
<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;"><code>where()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60点以上だけ残す</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;"><code>mask()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120歳超をNaNにする</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;"><code>replace()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>"未入力"</code>を<code>NaN</code>にする</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;"><code>fillna()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>NaN</code>を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;">条件抽出・<code>loc</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">売上が10000以上の行を抽出する</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;"><code>loc</code></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;"><code>np.where()</code>、<code>assign()</code>、<code>loc</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">合格・不合格列を作る</td>
</tr>
</tbody>
</table>
<p>この記事では、中心を<code>where()</code>と<code>mask()</code>に絞ります。<br/>
<code>replace()</code>は値そのものの置換、<code>fillna()</code>は欠損値を埋める処理、<code>loc</code>は行・列を指定する処理として分けて考えると整理しやすくなります。</p>
<h2><span id="toc13">locでの条件代入との違い</span></h2>
<p><code>loc</code>を使っても、条件に合う行だけ値を変更できます。</p>
<p>たとえば、売上が0未満の値を0にするなら、次のように書けます。</p>
<pre class="line-numbers"><code class="language-python">df_loc = df.copy()

df_loc.loc[df_loc["売上"] &lt; 0, "売上"] = 0

df_loc[["名前", "売上"]]</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">0</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;">18500</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;">0</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;">9200</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;">15000</td></tr></tbody></table>
<p><code>loc</code>は、<strong>条件に合う行と列を指定して、そこへ直接代入する</strong>イメージです。</p>
<p>一方、<code>where()</code>は「条件を満たす値を残し、それ以外を置き換えた結果を作る」イメージです。</p>
<pre class="line-numbers"><code class="language-python">df_where = df.copy()

df_where["売上"] = df_where["売上"].where(df_where["売上"] &gt;= 0, other=0)

df_where[["名前", "売上"]]</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">0</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;">18500</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;">0</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;">9200</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;">15000</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;"><code>loc</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>where()</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>mask()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件を満たす値をまとめて置き換えたい</td>
</tr>
</tbody>
</table>
<p>この記事の主役は<code>where()</code>と<code>mask()</code>なので、<code>loc</code>の詳細は別記事で学ぶのがおすすめです。</p>
<h2><span id="toc14">新しい列として結果を残すと確認しやすい</span></h2>
<p>初心者のうちは、いきなり元の列を上書きするより、<strong>新しい列として結果を残す</strong>ほうが確認しやすいです。</p>
<p>たとえば、売上の元データを残したまま、確認用の列を作ると、処理前後を並べて比較できます。</p>
<pre class="line-numbers"><code class="language-python">df_check = df.copy()

df_check["売上_修正案"] = df_check["売上"].where(df_check["売上"] &gt;= 0, other=0)
df_check["年齢_確認用"] = df_check["年齢"].mask(df_check["年齢"] &gt; 120)

df_check[["名前", "売上", "売上_修正案", "年齢", "年齢_確認用"]]</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;">12000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">24</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">24.0</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;">-500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">31</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">31.0</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;">18500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">18500</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">135</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">28</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">28.0</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;">9200</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">9200</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">42</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">42.0</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;">15000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">15000</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">19</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">19.0</td></tr></tbody></table>
<p>このように、元の列と処理後の列を並べると、どの値が変わったのかを確認しやすくなります。</p>
<p>特に、公開データや実務データでは、いきなり上書きすると元の状態が分からなくなることがあります。<br/>
最初は新しい列に結果を保存し、問題なければ上書きする流れがおすすめです。</p>
<h2><span id="toc15">よくあるミス1：代入しないと元のDataFrameは変わらない</span></h2>
<p><code>where()</code>や<code>mask()</code>は、実行しただけでは元のDataFrameを自動で書き換えません。</p>
<p>次のコードでは、<code>where()</code>の結果を表示しているだけなので、元の<code>df["売上"]</code>は変わりません。</p>
<pre class="line-numbers"><code class="language-python">df["売上"].where(df["売上"] &gt;= 0, other=0)

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></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;">12000</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;">-500</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;">18500</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;">0</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;">9200</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;">15000</td></tr></tbody></table>
<p>元のDataFrameを変更したい場合は、次のように代入します。</p>
<pre class="line-numbers"><code class="language-python">df_update = df.copy()

df_update["売上"] = df_update["売上"].where(df_update["売上"] &gt;= 0, other=0)

df_update[["名前", "売上"]]</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">0</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;">18500</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;">0</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;">9200</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;">15000</td></tr></tbody></table>
<p><code>where()</code>や<code>mask()</code>で処理した結果を残したい場合は、<strong>新しい列に入れるか、元の列に代入する</strong>必要があります。</p>
<h2><span id="toc16">よくあるミス2：条件式の向きが逆になる</span></h2>
<p><code>where()</code>と<code>mask()</code>で一番多いミスは、条件式の向きを逆にしてしまうことです。</p>
<p>たとえば、「60点以上だけ残したい」のに、次のように書くと意図と逆になります。</p>
<pre class="line-numbers"><code class="language-python">wrong = pd.DataFrame({
    "名前": df["名前"],
    "点数": df["点数"],
    "意図と逆になりやすい例": df["点数"].where(df["点数"] &lt; 60)
})

wrong</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">55.0</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">47.0</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td></tr></tbody></table>
<p>上の例では、<code>df["点数"] &lt; 60</code>という条件を書いているため、60点未満の値が残っています。</p>
<p>「60点以上だけ残したい」なら、条件は次のように書きます。</p>
<pre class="line-numbers"><code class="language-python">correct = pd.DataFrame({
    "名前": df["名前"],
    "点数": df["点数"],
    "60点以上だけ残す": df["点数"].where(df["点数"] &gt;= 60)
})

correct</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;">60点以上だけ残す</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;">82</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</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;">55</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">91</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">91.0</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;">47</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</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;">60</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">60.0</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">73.0</td></tr></tbody></table>
<p><code>where()</code>では、<strong>残したい条件を書く</strong>と覚えると、条件式の向きを間違えにくくなります。</p>
<p>逆に、<code>mask()</code>では、<strong>置き換えたい条件を書く</strong>と考えると分かりやすいです。</p>
<h2><span id="toc17">条件に合わない値をNaNにしたあとの流れ</span></h2>
<p><code>where()</code>や<code>mask()</code>で値を<code>NaN</code>にしたあと、そのまま終わりではありません。</p>
<p><code>NaN</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;">欠損値の数を確認したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>isnull().sum()</code></td>
</tr>
<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;"><code>fillna()</code></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;"><code>dropna()</code></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;"><code>groupby()</code>、<code>value_counts()</code></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>ここでは、年齢が120歳を超える値を<code>NaN</code>にしたあと、欠損値の数を確認してみます。</p>
<pre class="line-numbers"><code class="language-python">age_checked = df["年齢"].mask(df["年齢"] &gt; 120)

age_checked.isnull().sum()</code></pre>
<pre class="colab-output">np.int64(1)</pre>
<p>このように、<code>where()</code>や<code>mask()</code>は「欠損値を作る」ことがあります。<br/>
そのため、後続の<code>fillna()</code>や<code>dropna()</code>、集計・可視化とセットで考えると、データ分析の流れがつかみやすくなります。</p>
<h2><span id="toc18">np.where()には軽く触れる程度でよい</span></h2>
<p>条件に応じて値を変える方法として、<code>np.where()</code>もよく見かけます。</p>
<p>ただし、初心者が最初に学ぶ場合は、まず<code>pandas</code>の<code>where()</code>と<code>mask()</code>で、<strong>残す条件・置き換える条件</strong>の考え方を理解するのがおすすめです。</p>
<p><code>np.where()</code>は、たとえば「合格」「不合格」のような新しい列を作るときに便利です。</p>
<pre class="line-numbers"><code class="language-python">import numpy as np

df_np = df.copy()
df_np["判定"] = np.where(df_np["点数"] &gt;= 60, "合格", "再確認")

df_np[["名前", "点数", "判定"]]</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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">82</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;">55</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;">91</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;">47</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;">60</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;">73</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">合格</td></tr></tbody></table>
<p>ここでは、<code>np.where()</code>の詳細には深入りしません。</p>
<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;"><code>where()</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>mask()</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>np.where()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">条件に応じて新しい配列・列を作る</td>
</tr>
</tbody>
</table>
<p>新しい列の作り方を詳しく学びたい場合は、条件付き列追加の記事と合わせて学ぶと理解しやすくなります。</p>
<h2><span id="toc19">データ分析の流れではどこで使うか</span></h2>
<p><code>where()</code>と<code>mask()</code>は、単独で覚えるよりも、データ分析の流れの中で考えると使いどころが見えやすくなります。</p>
<p>たとえば、次のような流れです。</p>
<ol>
<li>CSVやExcelを読み込む</li>
<li><code>head()</code>で先頭を確認する</li>
<li><code>info()</code>や<code>describe()</code>で型・欠損値・統計量を確認する</li>
<li><code>unique()</code>や<code>value_counts()</code>で不自然な値を見つける</li>
<li><code>replace()</code>で表記ゆれを直す</li>
<li><code>where()</code>や<code>mask()</code>で条件に合わない値を整理する</li>
<li><code>fillna()</code>で欠損値を補う</li>
<li><code>groupby()</code>やグラフで集計・可視化する</li>
</ol>
<p>つまり、<code>where()</code>と<code>mask()</code>は、<strong>値を確認したあと、集計や可視化に進む前の前処理</strong>として使うと自然です。</p>
<p>特に、外れ値や不自然な値をそのまま集計すると、平均値やグラフが読みにくくなることがあります。<br/>
その前に、どの値を残し、どの値を確認対象にするかを整理するのが大切です。</p>
<h2><span id="toc20">まとめ</span></h2>
<p>この記事では、<code>pandas</code>の<code>where()</code>と<code>mask()</code>の使い方を解説しました。</p>
<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;"><code>where()</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>mask()</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>other</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;">条件式の考え方</td><td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>where()</code>は残したい条件、<code>mask()</code>は置き換えたい条件を書く</td></tr><tr><td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</code>との違い</td><td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</code>は特定の値そのものを置き換える</td></tr><tr><td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>fillna()</code>との違い</td><td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>fillna()</code>はすでにある欠損値を埋める</td></tr><tr><td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>loc</code>との違い</td><td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>loc</code>は条件に合う行・列を指定して代入する</td></tr><tr><td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>np.where()</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>NaN</code>にしたとき</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">整数列が<code>82.0</code>のように小数表示になることがある</td></tr></tbody></table>
<p><code>where()</code>と<code>mask()</code>は、条件に応じて値を残す・置き換えるための前処理で役立ちます。</p>
<p>最初は難しく感じるかもしれませんが、次の2つだけ覚えておけば大丈夫です。</p>
<ul>
<li><strong>残したい条件を書くなら<code>where()</code></strong></li>
<li><strong>置き換えたい条件を書くなら<code>mask()</code></strong></li>
</ul>
<p>この考え方を押さえると、条件に応じた値の整理がかなり分かりやすくなります。</p>
<h2><span id="toc21">次に読みたい関連記事</span></h2>
<p>今回の記事とあわせて読むと、Pandasの前処理の流れがつかみやすくなります。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
<li><a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></li>
<li><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-filtering/">pandas 条件抽出（filtering）入門｜AND/OR・query関数・複数条件の指定方法</a></li>
<li><a href="https://pythondatalab.com/pandas-loc/">【初心者向け】Pandasのlocで行や列をラベルで抽出する基本操作をやさしく解説【図解あり】</a></li>
<li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</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="toc22"> カテゴリから探す</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-1778074181310" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc23">where()とmask()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>where()</code>は、条件を満たす値を残し、条件を満たさない値を置き換えます。<br /><code>mask()</code>は逆に、条件を満たす値を置き換えます。<br />迷ったときは、<code>where()</code>は「残したい条件」、<code>mask()</code>は「置き換えたい条件」を書くと考えると分かりやすいです。</p>

</div>
</div>
<div id="faq-question-1778074208970" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc24">where()とreplace()はどう使い分けますか？</span></h3>
<div class="rank-math-answer ">

<p><code>replace()</code>は、特定の値そのものを置き換えるときに向いています。<br />たとえば、<code>"未入力"</code>を<code>NaN</code>にしたい場合は<code>replace()</code>が分かりやすいです。<br />一方、<code>60点未満</code>や<code>0未満</code>のように、条件式で判断したい場合は<code>where()</code>や<code>mask()</code>が向いています。</p>

</div>
</div>
<div id="faq-question-1778074229954" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc25">where()とlocで条件代入する方法は何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>loc</code>は、条件に合う行と列を指定して代入する方法です。<br /><code>where()</code>は、条件を満たす値を残し、条件を満たさない値を置き換えた結果を作る方法です。<br />どちらでも同じ結果を作れる場面はあります。<br />初心者のうちは、行・列を指定して変更したいなら<code>loc</code>、値を条件に応じて残す・置き換えるなら<code>where()</code>や<code>mask()</code>と考えると整理しやすいです。</p>

</div>
</div>
<div id="faq-question-1778074251258" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">where()で元のDataFrameが変わらないのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p><code>where()</code>を実行しただけでは、元のDataFrameは自動で書き換わりません。<br />処理結果を残したい場合は、次のように代入します。<br /><code>df["列名"] = df["列名"].where(条件, other=置き換える値)</code></p>
<p>元データを残したい場合は、新しい列に保存すると確認しやすいです。</p>

</div>
</div>
<div id="faq-question-1778074268378" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">条件に合わない値をNaNにするにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p><code>where()</code>で<code>other</code>を指定しなければ、条件を満たさない値は<code>NaN</code>になります。<br /><code>df["点数"].where(df["点数"] &gt;= 60)</code></p>
<p>この例では、60点以上はそのまま残り、60点未満は<code>NaN</code>になります。</p>

</div>
</div>
<div id="faq-question-1778074293682" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">np.where()とpandasのwhere()はどちらを使えばよいですか？</span></h3>
<div class="rank-math-answer ">

<p>まずは、<code>pandas</code>の<code>where()</code>と<code>mask()</code>で考え方を理解するのがおすすめです。<br />・条件を満たす値を残したい → <code>where()</code><br />・条件を満たす値を置き換えたい → <code>mask()</code><br />・条件に応じて新しい列を作りたい → <code>np.where()</code>も候補<br /><code>np.where()</code>は便利ですが、この記事では詳しい使い方には深入りしません。</p>

</div>
</div>
<div id="faq-question-1778074311090" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc29">複数条件でもwhere()は使えますか？</span></h3>
<div class="rank-math-answer ">

<p>使えます。<br />複数条件を使う場合は、各条件を<code>()</code>で囲み、AND条件は<code>&amp;</code>でつなぎます。<br /><code>df["点数"].where((df["点数"] &gt;= 60) &amp; (df["点数"] &lt;= 90))</code></p>
<p>ただし、複数条件は初心者が混乱しやすいため、最初は単一条件で<code>where()</code>と<code>mask()</code>の考え方を理解するのがおすすめです。</p>

</div>
</div>
<div id="faq-question-1778074342986" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">fillna()とは何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>fillna()</code>は、すでにある<code>NaN</code>を0や平均値などで埋めるメソッドです。<br />一方、<code>where()</code>や<code>mask()</code>は、条件に応じて値を<code>NaN</code>にしたり、別の値に置き換えたりできます。<br />流れとしては、<code>where()</code>や<code>mask()</code>で確認が必要な値を<code>NaN</code>にし、そのあと必要に応じて<code>fillna()</code>で補う、という使い方があります。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-where-mask/">pandas where()・mask()の使い方｜条件に応じて値を残す・置き換える方法</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-where-mask/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</title>
		<link>https://pythondatalab.com/pandas-to-numeric/</link>
					<comments>https://pythondatalab.com/pandas-to-numeric/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Wed, 06 May 2026 11:27:53 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2055</guid>

					<description><![CDATA[<p>pandasのto_numeric()で文字列の数字を数値に変換する方法を初心者向けに解説。object型で計算できない原因、errors="coerce"でNaNにする使い方、astype()との違い、カンマ・円付き金額の前処理まで具体例で紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-to-numeric/">pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</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 href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css" rel="stylesheet"/>
<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 {
    line-height: 1.8;
  }
  .colab-article p {
    margin: 0.8em 0;
  }
  .colab-article h2 {
    margin-top: 2.2em;
    margin-bottom: 0.8em;
  }
  .colab-article h3 {
    margin-top: 1.6em;
    margin-bottom: 0.6em;
  }
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers,
  .colab-article pre.colab-output {
    margin: 0 !important;
  }
  .colab-article pre.line-numbers {
    padding: 1em 1em 1em 3.8em;
    overflow-x: auto;
  }
  .colab-article pre.colab-output {
    padding: 0.8em 1em;
    overflow-x: auto;
    background: #f6f8fa;
    border: 1px solid #e5e7eb;
    color: #111827;
    white-space: pre;
  }
  .colab-article code {
    font-family: Consolas, Monaco, "Courier New", monospace;
  }
  .colab-article p code,
  .colab-article li code,
  .colab-article td code,
  .colab-article th code {
    padding: 0.1em 0.3em;
    border-radius: 4px;
    background: #f3f4f6;
  }
  .colab-article pre code {
    background: transparent;
    padding: 0;
  }
  .colab-article .colab-table-wrap {
    max-width: 100%;
    overflow-x: auto;
    margin: 0.8em 0;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 0;
  }
  .colab-article table.wp-block-table thead th {
    font-weight: 700;
    background: #f3f4f6;
  }
  .colab-article .colab-output-caption {
    margin: 0.8em 0 0.4em;
  }
  .colab-article .colab-point-box {
    margin: 1em 0;
    padding: 0.9em 1em;
    border-left: 4px solid #4b5563;
    background: #f9fafb;
  }
  .colab-article .colab-figure {
    margin: 1em 0;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>

<p>CSVやExcelを読み込んだあと、画面上では「1000」「2500」のように数字に見えるのに、<code>sum()</code>や<code>mean()</code>でうまく計算できないことがあります。</p>
<p>その原因の1つが、数字に見える列が、pandas上では<strong>文字列（object型）として扱われている</strong>ことです。</p>
<p>このようなときに役立つのが、<code>pd.to_numeric()</code>です。</p>
<p><code>pd.to_numeric()</code>は、<strong>数字に見える文字列を、計算できる数値型に変換するための関数</strong>です。特に、列の中に「不明」「-」「空欄」など、数値に変換できない値が混ざっている場合は、<code>errors="coerce"</code>を使うと安全に確認しながら前処理できます。</p>
<p>この記事では、<code>to_numeric()</code>の基本から、<code>astype()</code>との違い、<code>errors="coerce"</code>でNaNになる理由、変換後に集計や可視化へつなげる流れまで、初心者向けに順番に解説します。</p>
<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を学びます。</p>
<ul>
<li><code>pd.to_numeric()</code>で文字列の数字を数値に変換する方法</li>
<li>数字に見える列が<code>object</code>型になってしまう理由</li>
<li><code>errors="coerce"</code>で変換できない値を<code>NaN</code>にする考え方</li>
<li><code>to_numeric()</code>と<code>astype()</code>の違い</li>
<li>カンマ入り数値や「円」付きの金額を数値化する基本</li>
<li>変換後に<code>fillna()</code>、<code>dropna()</code>、<code>groupby()</code>、グラフ化へつなげる流れ</li>
</ul>
<p>この記事のゴールは、<strong>数字に見えるのに計算できない列を、<code>to_numeric()</code>で安全に数値化し、欠損確認・集計・可視化へ進める前処理の流れを理解すること</strong>です。</p>
<h2><span id="toc2">Pandas前処理の中での位置づけ</span></h2>
<p><code>to_numeric()</code>は、Pandasの前処理の中では「型を整える」場面で使います。</p>
<p>データ分析では、次のような流れで作業することが多いです。</p>
<ol>
<li>CSVやExcelを読み込む</li>
<li><code>head()</code>や<code>info()</code>でデータの状態を確認する</li>
<li>文字列になっている数値列を数値型に変換する</li>
<li>欠損値や変換できなかった値を処理する</li>
<li>集計やグラフ化に進む</li>
</ol>
<p><code>to_numeric()</code>は、特に3番目の「文字列になっている数値列を数値型に変換する」場面で役立ちます。</p>
<p>Pandasの基本的な流れを先に確認したい場合は、以下の記事も参考になります。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a></li>
<li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い</a></li>
<li><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門</a></li>
<li><a href="https://pythondatalab.com/pandas-read-excel/">pandas read_excel()の使い方</a></li>
</ul>
<h2><span id="toc3">まず結論：to_numeric()は「計算できる数値」に変換するために使う</span></h2>
<p><code>pd.to_numeric()</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;">変換前の値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">pandas上の見え方</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">問題</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"1000"</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>"2500"</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>"不明"</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>"-"</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>info()</code>や<code>dtypes</code>で型を確認し、必要に応じて<code>pd.to_numeric()</code>で数値化します。</p><div class="colab-point-box"><p><strong>判断基準：</strong>売上・数量・点数・金額のように「合計や平均を出したい列」は<code>to_numeric()</code>で数値化します。一方、商品コード・郵便番号・電話番号のような「識別のための列」は、数字に見えても文字列のまま扱うことがあります。</p></div>
<pre class="line-numbers"><code class="language-python">import pandas as pd

# サンプルデータ：売上が文字列として入っている例
df = pd.DataFrame({
    "商品": ["A", "B", "C", "D"],
    "売上": ["1000", "2500", "1800", "3200"],
    "数量": ["2", "5", "3", "4"]
})

display(df)
print(df.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1800</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品    object
売上    object
数量    object
dtype: object</code></pre>
<p>上の例では、<code>売上</code>列も<code>数量</code>列も見た目は数字ですが、<code>dtypes</code>を見ると<code>object</code>型になっています。</p>
<p><code>object</code>型は、文字列などが入っているときによく見られる型です。つまり、この状態では「数字のように見える文字列」として扱われています。</p>
<h2><span id="toc4">数字に見えるのに計算できない例</span></h2>
<p>文字列のまま集計しようとすると、思った結果にならないことがあります。</p>
<p>たとえば、文字列の列に対して<code>sum()</code>を使うと、数値の合計ではなく、文字列がつながってしまう場合があります。</p>
<pre class="line-numbers"><code class="language-python"># 文字列のままsum()すると、数値の合計ではなく文字列の連結になることがあります
print(df["売上"].sum())

# 平均は計算できないため、エラーになります
try:
    print(df["売上"].mean())
except Exception as e:
    print(type(e).__name__)
    print(e)
</code></pre>
<pre class="colab-output"><code>1000250018003200
TypeError
Could not convert string '1000250018003200' to numeric</code></pre>
<p>このように、見た目が数字でも、pandas上で文字列として扱われていると、集計や平均計算で困ることがあります。</p>
<p>そのため、CSVやExcelを読み込んだあとに計算がうまくいかない場合は、まず次の順番で確認します。</p>
<ol>
<li><code>info()</code>または<code>dtypes</code>で型を見る</li>
<li>数値として使いたい列が<code>object</code>型になっていないか確認する</li>
<li>必要なら<code>pd.to_numeric()</code>で数値型に変換する</li>
</ol>
<p>次に、実際に<code>to_numeric()</code>で変換してみます。</p>
<h2><span id="toc5">to_numeric()の基本的な使い方</span></h2>
<p><code>pd.to_numeric()</code>の基本形は、次のように書きます。</p>
<pre class="line-numbers"><code class="language-python">df["列名"] = pd.to_numeric(df["列名"])
</code></pre>
<p>ここでは、<code>売上</code>列と<code>数量</code>列を数値に変換します。</p>
<pre class="line-numbers"><code class="language-python">df_basic = df.copy()

df_basic["売上"] = pd.to_numeric(df_basic["売上"])
df_basic["数量"] = pd.to_numeric(df_basic["数量"])

display(df_basic)
print(df_basic.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1800</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品    object
売上     int64
数量     int64
dtype: object</code></pre>
<p>変換後は、<code>売上</code>列と<code>数量</code>列が数値型になりました。</p>
<p>この状態になれば、合計や平均を自然に計算できます。</p>
<pre class="line-numbers"><code class="language-python">print("売上合計:", df_basic["売上"].sum())
print("売上平均:", df_basic["売上"].mean())
print("数量合計:", df_basic["数量"].sum())
</code></pre>
<pre class="colab-output"><code>売上合計: 8500
売上平均: 2125.0
数量合計: 14</code></pre>
<h3><span id="toc6">複数列をまとめて数値に変換したい場合</span></h3>
<p>慣れてきたら、複数の列をまとめて<code>to_numeric()</code>で変換することもできます。</p>
<p>ただし、初心者のうちは、まず1列ずつ変換して、どの列で<code>NaN</code>が出たか確認する方が安全です。ここでは、<code>売上</code>列と<code>数量</code>列をまとめて変換する最小例だけ確認します。</p>
<pre class="line-numbers"><code class="language-python">df_multi = df.copy()

cols = ["売上", "数量"]
df_multi[cols] = df_multi[cols].apply(pd.to_numeric, errors="coerce")

display(df_multi)
print(df_multi.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1800</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品    object
売上     int64
数量     int64
dtype: object</code></pre>
<p>複数列をまとめて変換するとコードは短くなります。</p>
<p>一方で、どの列に変換できない値があったのか見落としやすくなることもあります。そのため、最初は1列ずつ確認し、慣れてきたら複数列の一括変換を使うのがおすすめです。</p>
<h2><span id="toc7">処理前後で見る：文字列の数字が数値になる</span></h2>
<p><code>to_numeric()</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;">状態</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上列の例</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">pandas上の型</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">できること</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>"1000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">object</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>1000</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">intまたはfloat</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">合計・平均・集計・グラフ化に使いやすい</td>
</tr>
</tbody>
</table></div>
<p>ポイントは、<strong>表示されている見た目ではなく、pandas上の型を確認すること</strong>です。</p>
<p>「数字に見えるから大丈夫」と判断せず、<code>info()</code>や<code>dtypes</code>で確認する習慣をつけると、前処理で迷いにくくなります。</p>
<h2><span id="toc8">変換できない値が混ざるとエラーになる</span></h2>
<p>実際のCSVやExcelでは、数値列の中に「不明」「-」「空欄」「error」などが混ざっていることがあります。</p>
<p>たとえば、次のような売上データを考えます。</p>
<pre class="line-numbers"><code class="language-python">df_dirty = pd.DataFrame({
    "商品": ["A", "B", "C", "D", "E"],
    "カテゴリ": ["食品", "食品", "日用品", "日用品", "食品"],
    "売上": ["1000", "2500", "不明", "3000", "-"],
    "数量": ["2", "5", "3", "error", "1"]
})

display(df_dirty)
print(df_dirty.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</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;">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;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2</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;">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;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5</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;">C</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>
</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;">D</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;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">error</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;">E</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;">&#8211;</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品      object
カテゴリ    object
売上      object
数量      object
dtype: object</code></pre>
<p><code>売上</code>列には「不明」や「-」が含まれています。<br/>
<code>数量</code>列には「error」が含まれています。</p>
<p>このような列をそのまま<code>pd.to_numeric()</code>で変換しようとすると、数値に変換できない値があるためエラーになります。</p>
<pre class="line-numbers"><code class="language-python">try:
    pd.to_numeric(df_dirty["売上"])
except Exception as e:
    print(type(e).__name__)
    print(e)
</code></pre>
<pre class="colab-output"><code>ValueError
Unable to parse string "不明" at position 2</code></pre>
<p>エラーが出ること自体は悪いことではありません。<br/>
むしろ、「この列には数値に変換できない値が混ざっている」と気づくきっかけになります。</p>
<p>ただし、実務では、変換できない値をいったん<code>NaN</code>にして確認したいことがよくあります。そこで使うのが、<code>errors="coerce"</code>です。</p>
<h2><span id="toc9">errors=&#8221;coerce&#8221;で変換できない値をNaNにする</span></h2>
<p><code>errors="coerce"</code>を指定すると、数値に変換できない値を<code>NaN</code>にできます。</p>
<pre class="line-numbers"><code class="language-python">pd.to_numeric(df["列名"], errors="coerce")
</code></pre>
<p><code>coerce</code>は「無理に変換する」という意味に近い指定です。<br/>
ただし、ここで大切なのは、<strong>エラーを隠すためではなく、変換できなかった値をNaNとして見つけるために使う</strong>という考え方です。</p>
<pre class="line-numbers"><code class="language-python">df_coerce = df_dirty.copy()

df_coerce["売上_数値"] = pd.to_numeric(df_coerce["売上"], errors="coerce")
df_coerce["数量_数値"] = pd.to_numeric(df_coerce["数量"], errors="coerce")

display(df_coerce)
print(df_coerce.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量_数値</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;">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;">1000</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;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2.0</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;">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;">2500</td>
<td style="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;">2500.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.0</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;">C</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3.0</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;">D</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;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">error</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</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;">E</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;">&#8211;</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.0</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品        object
カテゴリ      object
売上        object
数量        object
売上_数値    float64
数量_数値    float64
dtype: object</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;">変換前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>errors="coerce"</code>後</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">意味</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"1000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1000.0</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>"2500"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>2500.0</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>NaN</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>"3000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>3000.0</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>NaN</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数値に変換できなかった</td>
</tr>
</tbody>
</table></div>
<p><code>to_numeric()</code>後に<code>NaN</code>が出た場合、それは元データに数値化できない値が混ざっていたサインです。</p>
<h2><span id="toc10">NaNになった行を確認する</span></h2>
<p><code>errors="coerce"</code>を使ったあとに大切なのは、<code>NaN</code>になった行を確認することです。</p>
<p><code>NaN</code>になった値は、単なる欠損値ではなく、<strong>数値に変換できなかった値</strong>である可能性があります。</p>
<pre class="line-numbers"><code class="language-python"># 売上_数値がNaNになった行を確認
display(df_coerce[df_coerce["売上_数値"].isna()])

# 数量_数値がNaNになった行を確認
display(df_coerce[df_coerce["数量_数値"].isna()])
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量_数値</th>
</tr>
</thead>
<tbody>
<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;">C</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3.0</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;">E</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;">&#8211;</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.0</td>
</tr>
</tbody>
</table></div>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量_数値</th>
</tr>
</thead>
<tbody>
<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;">D</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;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">error</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</td>
</tr>
</tbody>
</table></div>
<p>この確認を入れることで、次に何をすべきか判断しやすくなります。</p>
<p>たとえば、</p>
<ul>
<li>「不明」は本当に欠損として扱ってよいのか</li>
<li>「-」は未入力を意味するのか</li>
<li>「error」は入力ミスなのか</li>
<li>行を除外するのか、0で埋めるのか、別途確認するのか</li>
</ul>
<p>といった判断ができます。</p>
<p><code>to_numeric()</code>は、数値化するだけでなく、<strong>データの汚れを見つける入口</strong>としても役立ちます。</p>
<h2><span id="toc11">errorsの違いを軽く整理する</span></h2>
<p><code>pd.to_numeric()</code>の<code>errors</code>では、初心者のうちは次の2つを押さえれば十分です。</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;">指定</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">動き</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">初心者向けの使いどころ</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>errors="raise"</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>errors="coerce"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">変換できない値を<code>NaN</code>にする</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">実務で混ざった不正値を見つけたいとき</td>
</tr>
</tbody>
</table></div>
<p>まずは、変換できない値があるとエラーになる<code>errors="raise"</code>で、データに問題があることを確認できます。</p>
<p>実務では、変換できない値を<code>NaN</code>にしてあとから確認したい場面が多いため、この記事では主に<code>errors="coerce"</code>を使って説明します。</p>
<p>なお、古い記事や古いpandas環境では<code>errors="ignore"</code>を見かけることがあります。<br/>
ただし、初心者向けの記事では通常の選択肢として覚える必要はありません。変換できない値を曖昧に残すより、<code>errors="coerce"</code>で<code>NaN</code>にして確認する方が、前処理の流れを理解しやすくなります。</p>
<h2><span id="toc12">to_numeric()とastype()の違い</span></h2>
<p>数値変換では、<code>astype()</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;">方法</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">向いている場面</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">注意点</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>astype()</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>to_numeric()</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>errors="coerce"</code>でNaNになる値を確認する必要がある</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>to_datetime()</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>replace()</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>astype()</code>、汚れた数値列を安全に扱うなら<code>to_numeric()</code>と考えると分かりやすいです。</p>
<pre class="line-numbers"><code class="language-python"># astype()は、きれいな値なら分かりやすく変換できます
df_astype_ok = pd.DataFrame({
    "売上": ["1000", "2500", "1800"]
})

df_astype_ok["売上"] = df_astype_ok["売上"].astype(int)
display(df_astype_ok)
print(df_astype_ok.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">1000</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;">2500</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;">1800</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>売上    int64
dtype: object</code></pre>
<pre class="line-numbers"><code class="language-python"># ただし、不明などが混ざるとastype()ではエラーになります
df_astype_ng = pd.DataFrame({
    "売上": ["1000", "2500", "不明", "3000"]
})

try:
    df_astype_ng["売上"].astype(int)
except Exception as e:
    print(type(e).__name__)
    print(e)
</code></pre>
<pre class="colab-output"><code>ValueError
invalid literal for int() with base 10: '不明'</code></pre>
<p>このように、<code>astype()</code>は値がきれいなときには便利です。</p>
<p>一方で、実際のCSVやExcelでは「不明」「-」「空欄」などが混ざることがあります。<br/>
そのような場合は、<code>pd.to_numeric(..., errors="coerce")</code>で変換できない値を<code>NaN</code>にして確認する方が、前処理の流れを作りやすくなります。</p>
<p><code>astype()</code>全体の使い方は、別記事の<a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方</a>で詳しく扱っています。</p>
<h2><span id="toc13">カンマ入り数値や「円」付きの金額を数値化する</span></h2>
<p>CSVやExcelでは、次のような値が入っていることがあります。</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;">値の例</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">そのまま数値化できるか</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">対応の考え方</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"1,000"</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>"2,500円"</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>"3000円"</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>"不明"</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>errors="coerce"</code>でNaNにして確認</td>
</tr>
</tbody>
</table></div>
<p>ここでは、複雑な正規表現には深入りせず、基本的な置換だけで考えます。</p>
<pre class="line-numbers"><code class="language-python">df_money = pd.DataFrame({
    "商品": ["A", "B", "C", "D"],
    "売上": ["1,000", "2,500円", "3000円", "不明"]
})

display(df_money)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1,000</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2,500円</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000円</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;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">不明</td>
</tr>
</tbody>
</table></div>
<pre class="line-numbers"><code class="language-python">df_money_clean = df_money.copy()

# カンマと「円」を取り除く
df_money_clean["売上_整形後"] = (
    df_money_clean["売上"]
    .str.replace(",", "", regex=False)
    .str.replace("円", "", regex=False)
)

# 数値に変換する
df_money_clean["売上_数値"] = pd.to_numeric(df_money_clean["売上_整形後"], errors="coerce")

display(df_money_clean)
print(df_money_clean.dtypes)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_整形後</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1,000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000.0</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2,500円</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500.0</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000円</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</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;">D</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;">NaN</td>
</tr>
</tbody>
</table></div>
<pre class="colab-output"><code>商品         object
売上         object
売上_整形後     object
売上_数値     float64
dtype: object</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;">元の値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">整形後</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数値変換後</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"1,000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"1000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>1000.0</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"2,500円"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"2500"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>2500.0</code></td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"3000円"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>"3000"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>3000.0</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>"不明"</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>NaN</code></td>
</tr>
</tbody>
</table></div>
<p>ここでのポイントは、<code>replace()</code>や<code>str.replace()</code>で文字を整えたあと、最後に<code>to_numeric()</code>で数値型にすることです。</p>
<p>置換処理そのものを詳しく学びたい場合は、<a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方</a>も参考になります。</p>
<h2><span id="toc14">変換後のNaNをどう扱うか</span></h2>
<p><code>to_numeric(errors="coerce")</code>で<code>NaN</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;">方法</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">使う場面</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>fillna()</code></td>
<td style="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;">未入力の売上を0として扱う</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>dropna()</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>ただし、どちらが正しいかはデータの意味によって変わります。</p>
<p>たとえば、売上の「不明」を0円とみなしてよいとは限りません。<br/>
0で埋める前に、NaNになった理由を確認することが大切です。</p>
<pre class="line-numbers"><code class="language-python">df_after = df_coerce.copy()

# 例1：売上_数値のNaNを0で埋める
df_fill = df_after.copy()
df_fill["売上_数値"] = df_fill["売上_数値"].fillna(0)

print("NaNを0で埋めた例")
display(df_fill)

# 例2：売上_数値がNaNの行を除外する
df_drop = df_after.dropna(subset=["売上_数値"])

print("売上_数値がNaNの行を除外した例")
display(df_drop)
</code></pre>
<p class="colab-output-caption"><strong>NaNを0で埋めた例</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量_数値</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;">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;">1000</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;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2.0</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;">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;">2500</td>
<td style="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;">2500.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.0</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;">C</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;">0.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3.0</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;">D</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;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">error</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</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;">E</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;">&#8211;</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;">0.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1.0</td>
</tr>
</tbody>
</table></div>
<p class="colab-output-caption"><strong>売上_数値がNaNの行を除外した例</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数量_数値</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;">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;">1000</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;">1000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2.0</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;">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;">2500</td>
<td style="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;">2500.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">5.0</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;">D</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;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">error</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">NaN</td>
</tr>
</tbody>
</table></div>
<p><code>fillna()</code>と<code>dropna()</code>は、どちらもよく使う欠損処理です。</p>
<ul>
<li><p>欠損値を埋める処理を詳しく学びたい場合：<br/>
<a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方</a></p>
</li>
<li><p>欠損行を削除する処理を詳しく学びたい場合：<br/>
<a href="https://pythondatalab.com/pandas-drop/">pandas dropna()・drop_duplicates()・drop()の使い方</a></p>
</li>
</ul>
<p>今回の記事では、<code>to_numeric()</code>で数値化したあとに、必要に応じて欠損処理へ進む流れだけ押さえれば十分です。</p>
<h2><span id="toc15">数値化できると集計や可視化に進みやすくなる</span></h2>
<p><code>to_numeric()</code>で数値化できると、合計・平均・グループ別集計・グラフ化に進みやすくなります。</p>
<p>ここでは、カテゴリ別に売上合計を出す例を見てみます。</p>
<pre class="line-numbers"><code class="language-python"># 集計用のデータを作る
# グラフの文字化けを避けるため、カテゴリ名は英語にしています
df_sales = pd.DataFrame({
    "商品": ["A", "B", "C", "D", "E", "F"],
    "カテゴリ": ["Food", "Food", "Daily goods", "Daily goods", "Food", "Daily goods"],
    "売上": ["1000", "2500", "不明", "3000", "1200", "1800"]
})

# 売上を数値化
df_sales["売上_数値"] = pd.to_numeric(df_sales["売上"], errors="coerce")

display(df_sales)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">商品</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</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;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Food</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1000.0</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;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Food</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">2500.0</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;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Daily goods</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;">NaN</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;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Daily goods</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">3000.0</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;">E</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Food</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1200.0</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;">F</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">Daily goods</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">1800.0</td>
</tr>
</tbody>
</table></div>
<pre class="line-numbers"><code class="language-python"># NaNを除いてカテゴリ別に売上を集計
category_sales = (
    df_sales
    .dropna(subset=["売上_数値"])
    .groupby("カテゴリ")["売上_数値"]
    .sum()
    .reset_index()
)

display(category_sales)
</code></pre>
<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">カテゴリ</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">売上_数値</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;">Daily goods</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4800.0</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;">Food</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">4700.0</td>
</tr>
</tbody>
</table></div>
<p>このように、文字列だった売上列を数値化すると、<code>groupby()</code>でカテゴリ別に集計できるようになります。</p>
<p><code>groupby()</code>を詳しく学びたい場合は、<a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方</a>も参考になります。</p>
<pre class="line-numbers"><code class="language-python">import matplotlib.pyplot as plt

# 数値化した結果を棒グラフで確認
category_sales.plot(kind="bar", x="カテゴリ", y="売上_数値", legend=False)
plt.title("Sales by Category")
plt.xlabel("Category")
plt.ylabel("Sales")
plt.show()
</code></pre>
<figure class="colab-figure">
<img decoding="async" alt="数値化した売上をカテゴリ別に集計した棒グラフ" src="images/figure1.png"/>
<figcaption>数値化した売上をカテゴリ別に集計した棒グラフ</figcaption>
</figure>
<p>Google Colabでは、日本語フォントの設定をしていないとグラフ内の日本語が文字化けすることがあります。</p>
<p>この記事では<code>to_numeric()</code>で数値化したあとにグラフ化へ進める流れを確認することが目的なので、グラフ用のカテゴリ名とラベルは英語にしています。</p>
<p>グラフ化そのものはこの記事の主題ではありませんが、数値列が正しく数値型になっていると、Matplotlibで可視化しやすくなります。</p>
<p>棒グラフの作り方を詳しく学びたい場合は、<a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a>へ進むと理解がつながります。</p>
<h3><span id="toc16">補足：グラフを日本語表示したい場合</span></h3>
<p>Google Colabでグラフ内の日本語を表示したい場合は、<code>japanize-matplotlib</code>を使う方法もあります。</p>
<pre class="line-numbers"><code class="language-python">!pip install japanize-matplotlib &gt; /dev/null
import japanize_matplotlib
</code></pre>
<p>ただし、この記事の主題は<code>to_numeric()</code>で数値化する前処理です。<br/>
そのため、本文ではグラフの日本語表示設定には深入りせず、数値化後に集計・可視化へ進める流れの確認にとどめます。</p>
<p>Matplotlibの見やすいグラフ設定を詳しく学びたい場合は、関連記事のMatplotlib入門記事へ進んでください。</p>
<h2><span id="toc17">すべてのobject型を数値化すればよいわけではない</span></h2>
<p>ここまで、<code>object</code>型の数値列を<code>to_numeric()</code>で変換する方法を見てきました。</p>
<p>ただし、すべての<code>object</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;">列の例</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">数値化しない方がよい理由</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>
</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>
</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;">先頭の0が消えると困る</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>
</tr>
</tbody>
</table></div>
<p><code>to_numeric()</code>を使う前に、<strong>その列を計算に使うのか</strong>を確認することが大切です。</p>
<p>売上、数量、点数、金額のように合計や平均を出したい列なら数値化します。<br/>
一方で、IDやコードのように識別のための列は、文字列のまま扱うこともあります。</p>
<h2><span id="toc18">よくあるミスと確認ポイント</span></h2>
<p><code>to_numeric()</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;">よくあるミス</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">原因</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">確認すること</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;"><code>dtypes</code>や<code>info()</code>を見る</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>astype(int)</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>to_numeric(errors="coerce")</code>を使う</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">変換後に<code>NaN</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>isna()</code>で行を確認する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">intではなくfloatになる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;"><code>NaN</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>,</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;">数値変換と日付変換を混同している</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em; border: 1px solid #ddd;">日付は<code>to_datetime()</code>を使う</td>
</tr>
</tbody>
</table></div>
<p>日付変換については、<a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方</a>で詳しく解説しています。</p>
<h2><span id="toc19">まとめ</span></h2>
<p>この記事では、<code>pandas to_numeric()</code>の使い方を解説しました。</p>
<p>ポイントを整理します。</p>
<ul>
<li><code>pd.to_numeric()</code>は、数字に見える文字列を計算できる数値型に変換する関数</li>
<li>CSVやExcelを読み込んだあと、数値列が<code>object</code>型になることがある</li>
<li>変換前後は<code>info()</code>や<code>dtypes</code>で確認する</li>
<li>変換できない値が混ざる場合は、<code>errors="coerce"</code>で<code>NaN</code>にできる</li>
<li><code>NaN</code>になった値は、変換できなかった値として確認する</li>
<li>きれいな値なら<code>astype()</code>、汚れた数値列を安全に扱うなら<code>to_numeric()</code>が使いやすい</li>
<li>カンマや「円」付きの値は、文字を整えてから数値化する</li>
<li>まずは1列ずつ確認し、慣れてきたら複数列の一括変換も使える</li>
<li>数値化できると、<code>sum()</code>、<code>mean()</code>、<code>groupby()</code>、Matplotlibによる可視化へ進みやすくなる</li>
</ul>
<p><code>to_numeric()</code>は、派手な機能ではありませんが、データ分析の前処理ではとても重要です。</p>
<p>「数字に見えるのに計算できない」と感じたら、まず<code>dtypes</code>で型を確認し、必要に応じて<code>pd.to_numeric()</code>で数値化してみましょう。</p>
<h2><span id="toc20">次に読みたい関連記事</span></h2>
<p>今回の記事とあわせて読むと、Pandasの前処理から集計・可視化までの流れがつながりやすくなります。</p>
<ul>
<li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a></li>
<li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
<li><a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方｜文字列・数値への型変換とエラー対処を初心者向けに解説</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-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></li>
<li><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-drop/">pandas dropna()・drop_duplicates()・drop()の使い方</a></li>
<li><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門</a></li>
<li><a href="https://pythondatalab.com/pandas-read-excel/">pandas read_excel()の使い方｜Excelファイル読み込み・sheet_name・usecolsを解説</a></li>
<li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
<li><a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a></li>
<li><a href="https://pythondatalab.com/pandas-roadmap/">Pandas初心者向け学習ロードマップ</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="toc21"> カテゴリから探す</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>if (window.Prism) { Prism.highlightAll(); }</script>
</div>



<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1778066673532" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc22"> to_numeric()とastype()は何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>astype()</code>は、値がきれいで変換先の型を明示したいときに使いやすい方法です。<br />一方、<code>to_numeric()</code>は、数字に見える文字列を数値化したいときに向いています。特に、「不明」「-」「空欄」などが混ざる可能性がある列では、<code>errors="coerce"</code>を使って、変換できない値を<code>NaN</code>として確認できます。<br />ざっくり言うと、<strong>きれいな型変換は<code>astype()</code>、汚れた数値列の安全な数値化は<code>to_numeric()</code></strong>と考えると分かりやすいです。</p>

</div>
</div>
<div id="faq-question-1778066697099" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc23">errors=&#8221;coerce&#8221;とは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>errors="coerce"</code>は、数値に変換できない値を<code>NaN</code>にする指定です。<br />たとえば、<code>"1000"</code>は数値に変換できますが、<code>"不明"</code>や<code>"-"</code>はそのままでは数値にできません。<br />そのような値を<code>NaN</code>にして、あとで確認できるようにするのが<code>errors="coerce"</code>です。</p>

</div>
</div>
<div id="faq-question-1778066711020" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc24">to_numeric()でNaNになるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>元の値に、数値へ変換できない文字が含まれているためです。<br />たとえば、<code>"不明"</code>、<code>"error"</code>、<code>"-"</code>、<code>"1,000"</code>、<code>"3000円"</code>などは、そのままでは数値化できない場合があります。<br /><code>NaN</code>になった行は、<code>isna()</code>で確認して、置換するのか、0で埋めるのか、除外するのかを判断します。</p>

</div>
</div>
<div id="faq-question-1778066724075" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc25">カンマ入りの「1,000」はそのまま数値にできますか？</span></h3>
<div class="rank-math-answer ">

<p>そのままでは変換できないことがあります。<br />基本的には、先にカンマを取り除いてから<code>to_numeric()</code>を使います。<br /><code>df["売上"] = df["売上"].str.replace(",", "", regex=False) </code><br /><code>df["売上"] = pd.to_numeric(df["売上"], errors="coerce")</code></p>

</div>
</div>
<div id="faq-question-1778066760746" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">「円」が付いた金額はどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>カンマや「円」を取り除いてから、<code>to_numeric()</code>で数値化します。本文の例と同じく、最後に<code>errors="coerce"</code>で変換できない値を確認すると安全です。<br /><code>df["金額"] = ( </code><br />　　<code>df["金額"] </code><br />　　<code>.str.replace(",", "", regex=False) </code><br />　　<code>.str.replace("円", "", regex=False)</code><br /><code> )</code><br /><code> df["金額"] = pd.to_numeric(df["金額"], errors="coerce")</code></p>

</div>
</div>
<div id="faq-question-1778066842394" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">read_csvで読み込んだ列がobject型になるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>列の中に、数値だけでなく文字や空欄、記号が混ざっていると、pandasがその列を文字列寄りの<code>object</code>型として読み込むことがあります。<br />たとえば、売上列に<code>"1000"</code>、<code>"2500"</code>、<code>"不明"</code>が混ざっていると、数値列として扱いにくくなります。<br />その場合は、読み込んだあとに<code>info()</code>や<code>dtypes</code>で確認し、必要に応じて<code>to_numeric()</code>で変換します。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-to-numeric/">pandas to_numeric()の使い方｜文字列の数字を数値に変換する方法</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-to-numeric/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas read_excel()の使い方｜Excelファイル読み込み・sheet_name・usecolsを解説</title>
		<link>https://pythondatalab.com/pandas-read-excel/</link>
					<comments>https://pythondatalab.com/pandas-read-excel/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Tue, 05 May 2026 15:37:12 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2050</guid>

					<description><![CDATA[<p>pandasのread_excel()でExcelファイルを読み込む方法を初心者向けに解説。sheet_nameでシート指定、usecolsで列指定、header・skiprowsで見出し行を調整する方法、Colabでの読み込み、CSV化の考え方まで紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-read-excel/">pandas read_excel()の使い方｜Excelファイル読み込み・sheet_name・usecolsを解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[

<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">
<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 {
    line-height: 1.8;
    word-break: normal;
    overflow-wrap: anywhere;
  }
  .colab-article p {
    margin: 0 0 1em;
  }
  .colab-article h1,
  .colab-article h2,
  .colab-article h3,
  .colab-article h4,
  .colab-article h5,
  .colab-article h6 {
    line-height: 1.5;
    margin: 1.6em 0 0.7em;
  }
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers {
    margin: 0 !important;
    padding: 1em !important;
    overflow-x: auto;
    border-radius: 6px;
  }
  .colab-article code {
    font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  }
  .colab-article table.wp-block-table {
    width: auto;
    max-width: 100%;
    border-collapse: collapse;
    display: block;
    overflow-x: auto;
    margin: 1em 0;
  }
  .colab-article table.wp-block-table th,
  .colab-article table.wp-block-table td {
    border: 1px solid #ddd;
    white-space: nowrap;
    padding: 0.2em 0.4em;
  }
  .colab-article table.wp-block-table th:first-child,
  .colab-article table.wp-block-table td:first-child {
    min-width: 3em;
    white-space: nowrap;
    padding: 0.2em 0.4em;
  }
  .colab-article figure.colab-figure {
    margin: 1.5em 0;
  }
  .colab-article figure.colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>
<script>
  if (window.Prism) {
    Prism.highlightAll();
  }
</script>

<div class="colab-article">


<p>Pythonでデータ分析を始めると、CSVファイルだけでなく、Excelファイルを読み込みたい場面もよくあります。</p>
<p>たとえば、次のような場面です。</p>
<ul>
<li>会社や学校から配布されたデータが <code>.xlsx</code> 形式になっている</li>
<li>Excelファイルの中に複数のシートがある</li>
<li>必要な列だけ読み込みたい</li>
<li>1行目にタイトルや説明文があり、表の見出しがずれている</li>
<li>読み込んだあと、日付や数値の型が合っているか確認したい</li>
</ul>
<p>結論からいうと、Excelファイルをpandasで読み込むには、まず <code>pd.read_excel(&quot;ファイル名.xlsx&quot;)</code> を使います。</p>
<p>そのうえで、必要に応じて次のように指定します。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>やりたいこと</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">使う指定</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">複数シートから特定のシートを読み込みたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>sheet_name</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">必要な列だけ読み込みたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>usecols</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">見出し行がずれている</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>header</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">表の上に説明行がある</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>skiprows</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">特定の列をインデックスにしたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>index_col</code></td>
</tr>
</tbody>
</table>
<p>この記事では、Google Colabで手元のExcelファイルをアップロードして読み込む方法にも軽く触れつつ、練習用のサンプルExcelファイルを作りながら、<code>read_excel()</code> の基本、<code>sheet_name</code>・<code>usecols</code>・<code>header</code>・<code>skiprows</code> の使いどころ、読み込み後に確認すべきポイントまでを初心者向けに整理します。</p>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を扱います。</p>
<ul>
<li>Google Colabで手元のExcelファイルをアップロードして読み込む基本</li>
<li><code>pd.read_excel()</code> でExcelファイルをDataFrameとして読み込む基本</li>
<li><code>sheet_name</code> でシートを指定する方法</li>
<li><code>usecols</code> で必要な列だけ読み込む方法</li>
<li><code>header</code>・<code>skiprows</code> で見出し行や不要な説明行を調整する方法</li>
<li><code>read_excel()</code> と <code>read_csv()</code> の違い</li>
<li>読み込んだあとに <code>head()</code>・<code>info()</code>・<code>describe()</code> で確認する流れ</li>
<li>Excel読み込み後に、列名変更・型変換・日付変換・欠損値処理へ進む考え方</li>
</ul>
<p>Excelファイルを読むこと自体がゴールではありません。<br />
読み込んだ表をDataFrameとして確認し、前処理・抽出・集計・可視化へ進める状態にすることが大切です。</p>

<h2><span id="toc2">Excelファイルを読み込んだ後の流れ</span></h2>
<p>Excelファイルの読み込みは、データ分析の最初の入口です。<br />
ただし、<code>read_excel()</code> で読み込んで終わりではありません。</p>
<p>読み込んだ表をDataFrameとして確認し、必要に応じて列名・型・日付・欠損値を整えてから、抽出・集計・可視化へ進む流れが大切です。</p>
<p>学習の流れとしては、次のように考えると自然です。</p>
<ol>
<li>Google ColabでPythonを動かす</li>
<li><code>read_excel()</code> でExcelファイルをDataFrameとして読み込む</li>
<li><code>head()</code>・<code>info()</code>・<code>describe()</code> で中身を確認する</li>
<li>必要に応じて列名・型・日付・欠損値を整える</li>
<li>条件抽出・集計・可視化へ進む</li>
</ol>
<p>CSVファイルを読み込む場合は <code>read_csv()</code>、Excelファイルを読み込む場合は <code>read_excel()</code> を使います。<br />
この記事では、ExcelファイルをDataFrameとして読み込み、分析しやすい形に整える入口までを中心に説明します。</p>

<h2><span id="toc3">read_excel()とは？</span></h2>
<p><code>read_excel()</code> は、ExcelファイルをpandasのDataFrameとして読み込むための関数です。</p>
<p>基本形は次のとおりです。</p>
<pre><code class="language-python">pd.read_excel(&quot;ファイル名.xlsx&quot;)
</code></pre>
<p>シンプルなExcelファイルであれば、まずはこの形で読み込めます。</p>
<p>ただし、実際のExcelファイルでは、次のような調整が必要になることがあります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>困る場面</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="white-space: nowrap; padding: 0.2em 0.4em;">シートが複数ある</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>sheet_name</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">どのシートを読むか指定する</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列が多すぎる</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>usecols</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">必要な列だけ読む</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">1行目が見出しではない</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>header</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">どの行を列名として使うか指定する</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">表の上に説明行がある</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>skiprows</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">不要な行を読み飛ばす</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">ID列を行ラベルにしたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>index_col</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">特定の列をインデックスにする</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">見出しがない表に列名を付けたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>names</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列名を自分で指定する</td>
</tr>
</tbody>
</table>
<p>初心者のうちは、最初からすべての引数を覚える必要はありません。<br />
まずは「何に困っているか」と「どの引数で調整するか」を対応させて理解しましょう。</p>
<p>なお、<code>names</code> は列名を自分で付けたいときに使える引数ですが、初心者のうちはまず <code>header</code> で見出し行を正しく読み込む方法を優先すると理解しやすいです。</p>

<h2><span id="toc4">Google Colabで自分のExcelファイルを読み込む場合</span></h2>
<p>自分のパソコンにあるExcelファイルをGoogle Colabで読み込みたい場合は、まずファイルをアップロードします。</p>
<p>なお、この章の <code>from google.colab import files</code> は、Google Colabで実行する場合の方法です。ローカルのJupyter Notebookを使っている場合は、ExcelファイルをNotebookと同じフォルダに置いて読み込めば大丈夫です。</p>
<p>※この章は、自分のパソコンにあるExcelファイルをアップロードして読み込む場合の手順です。記事内で作成するサンプルExcelを使う場合は、この章のコードは実行せず、次の「練習用のExcelファイルを用意する」章から実行してください。</p>
<p>次のコードを実行すると、ファイル選択ボタンが表示されます。<br />
読み込みたい <code>.xlsx</code> ファイルを選んでアップロードしてください。</p>

<pre class="line-numbers"><code class="language-python">from google.colab import files

uploaded = files.upload()
</code></pre>

<p>アップロードできたら、ファイル名を指定して <code>read_excel()</code> で読み込みます。</p>
<p>たとえば、アップロードしたファイル名が <code>sales_sample.xlsx</code> の場合は、次のように書きます。</p>

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

df = pd.read_excel(&quot;sales_sample.xlsx&quot;)
df.head()
</code></pre>

<p>この記事では、読者が同じコードをそのまま試せるように、次の章で練習用のExcelファイルを作成してから読み込みます。<br />
すでに自分のExcelファイルがある場合は、このあとのサンプル作成部分を飛ばして、自分のファイル名に置き換えて進めても大丈夫です。</p>

<h2><span id="toc5">練習用のExcelファイルを用意する</span></h2>
<p>ここでは、記事内で同じ結果を再現できるように、練習用のExcelファイルを作成します。</p>
<p>このコードは「Excelファイルを用意するための準備」です。<br />
自分のExcelファイルを使う場合は、この章を飛ばして、ファイル名だけ自分のものに置き換えて進めてください。</p>
<p>サンプルは、<code>sheet_name</code>・<code>header</code>・<code>skiprows</code> を説明できる最小限の内容にしています。</p>
<p>なお、Excelファイルの作成や読み込みでは、環境によって <code>openpyxl</code> が必要になることがあります。<br />
Google Colabではそのまま使えることが多いですが、エラーが出た場合は後半の「openpyxlが必要というエラーが出る」を確認してください。</p>

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

# 練習用の売上データ
sales_df = pd.DataFrame({
    &quot;売上日&quot;: [&quot;2025-04-01&quot;, &quot;2025-04-02&quot;, &quot;2025-04-03&quot;],
    &quot;店舗&quot;: [&quot;東京店&quot;, &quot;大阪店&quot;, &quot;東京店&quot;],
    &quot;商品&quot;: [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;],
    &quot;売上金額&quot;: [120000, 3000, 8000],
    &quot;数量&quot;: [1, 2, 1]
})

# 複数シートの例に使う商品マスタ
master_df = pd.DataFrame({
    &quot;商品&quot;: [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;],
    &quot;カテゴリ&quot;: [&quot;PC&quot;, &quot;周辺機器&quot;, &quot;周辺機器&quot;]
})

file_path = &quot;sales_sample.xlsx&quot;

# 練習用のExcelファイルを作成
with pd.ExcelWriter(file_path, engine=&quot;openpyxl&quot;) as writer:
    sales_df.to_excel(writer, sheet_name=&quot;売上データ&quot;, index=False)
    master_df.to_excel(writer, sheet_name=&quot;商品マスタ&quot;, index=False)

    # 説明行が上にあるExcelを再現するため、3行目から表を書き込む
    sales_df.to_excel(writer, sheet_name=&quot;説明行あり&quot;, index=False, startrow=2)
    ws = writer.sheets[&quot;説明行あり&quot;]
    ws[&quot;A1&quot;] = &quot;2025年4月 売上レポート&quot;
    ws[&quot;A2&quot;] = &quot;※この行は説明行です。&quot;

file_path
</code></pre>

<pre>&#x27;sales_sample.xlsx&#x27;</pre>

<h2><span id="toc6">まずは基本形でExcelファイルを読み込む</span></h2>
<p>一番シンプルな読み込み方は、<code>pd.read_excel()</code> にExcelファイル名を指定する方法です。</p>
<p>次のコードでは、Excelファイルの先頭シートをDataFrameとして読み込みます。</p>

<pre class="line-numbers"><code class="language-python">df = pd.read_excel(&quot;sales_sample.xlsx&quot;)
df
</code></pre>

  <div id="df-4f8cec06-3b54-48b7-a374-8a3f9fa0950a" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-4f8cec06-3b54-48b7-a374-8a3f9fa0950a')"
            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-4f8cec06-3b54-48b7-a374-8a3f9fa0950a button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-4f8cec06-3b54-48b7-a374-8a3f9fa0950a');
        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="id_ba0d41f1-6081-4ab1-8769-f867c623dfcd">
    <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('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_ba0d41f1-6081-4ab1-8769-f867c623dfcd button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<p>Excelファイルを読み込むと、pandasではDataFrameとして扱えます。<br />
ここで大切なのは、読み込んで終わりにしないことです。</p>
<p>読み込んだ直後は、まず次の3つを確認しましょう。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>確認したいこと</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="white-space: nowrap; padding: 0.2em 0.4em;">先頭の数行</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>head()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">想定した表になっているか</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列名・型・欠損値</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>info()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付や数値の型が合っているか</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">数値列の統計量</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>describe()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">極端な値がないか</td>
</tr>
</tbody>
</table>
<p>Excelでは見た目が整っていても、pandasで読み込むと型や列名が想定と違うことがあります。<br />
そのため、読み込み後の確認はとても重要です。</p>

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

  <div id="df-62387e06-f14a-45de-b63d-e084425f726d" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-62387e06-f14a-45de-b63d-e084425f726d')"
            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-62387e06-f14a-45de-b63d-e084425f726d button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-62387e06-f14a-45de-b63d-e084425f726d');
        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>

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

<pre>&lt;class &#x27;pandas.core.frame.DataFrame&#x27;&gt;
RangeIndex: 3 entries, 0 to 2
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   売上日     3 non-null      object
 1   店舗      3 non-null      object
 2   商品      3 non-null      object
 3   売上金額    3 non-null      int64 
 4   数量      3 non-null      int64 
dtypes: int64(2), object(3)
memory usage: 252.0+ bytes
</pre>

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

  <div id="df-e0b8ab0a-7a8c-437c-a946-ba53c1f76e36" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">count</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3.000000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">mean</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">43666.666667</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.333333</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">std</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">66153.861061</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.577350</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">min</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3000.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.000000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">25%</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5500.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.000000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">50%</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.000000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">75%</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">64000.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1.500000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">max</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000.000000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2.000000</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-e0b8ab0a-7a8c-437c-a946-ba53c1f76e36')"
            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-e0b8ab0a-7a8c-437c-a946-ba53c1f76e36 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-e0b8ab0a-7a8c-437c-a946-ba53c1f76e36');
        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="toc7">sheet_nameで読み込むシートを指定する</span></h2>
<p>Excelファイルには、複数のシートが入っていることがあります。<br />
この場合は、<code>sheet_name</code> を使って、どのシートを読み込むか指定します。</p>
<p><code>sheet_name</code> は列名ではなく、Excelの下部に表示される「シート名」を指定するための引数です。</p>

<pre class="line-numbers"><code class="language-python">sales = pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=&quot;売上データ&quot;)
sales
</code></pre>

  <div id="df-8d2cd5fd-ce20-409b-8a92-3f200328e1ca" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-8d2cd5fd-ce20-409b-8a92-3f200328e1ca')"
            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-8d2cd5fd-ce20-409b-8a92-3f200328e1ca button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-8d2cd5fd-ce20-409b-8a92-3f200328e1ca');
        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="id_5c0d3ea5-255a-41ed-b9de-e3e281880089">
    <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')"
            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_5c0d3ea5-255a-41ed-b9de-e3e281880089 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<pre class="line-numbers"><code class="language-python">master = pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=&quot;商品マスタ&quot;)
master
</code></pre>

  <div id="df-8dd83152-72ff-4ef5-8442-88347b0788f2" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td>
    </tr>
    <tr>
      <th style="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;">周辺機器</td>
    </tr>
    <tr>
      <th style="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;">周辺機器</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-8dd83152-72ff-4ef5-8442-88347b0788f2')"
            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-8dd83152-72ff-4ef5-8442-88347b0788f2 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-8dd83152-72ff-4ef5-8442-88347b0788f2');
        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="id_68bc1f55-0b19-4b9a-8b13-b116e1e357bf">
    <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('master')"
            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_68bc1f55-0b19-4b9a-8b13-b116e1e357bf button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<p>シート名ではなく、シート番号で指定することもできます。<br />
ただし、初心者のうちはシート名で指定したほうが、あとから見返したときに意味がわかりやすいです。</p>
<pre><code class="language-python">pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=0)
</code></pre>
<p>複数シートをまとめて読み込む方法もありますが、この記事では深入りしません。<br />
まずは「必要なシートを1つ選んで読み込む」ことを優先しましょう。</p>

<h2><span id="toc8">usecolsで必要な列だけ読み込む</span></h2>
<p>Excelファイルには、分析に使わない列がたくさん入っていることがあります。<br />
必要な列だけ読み込みたい場合は、<code>usecols</code> を使います。</p>
<p>たとえば、売上日の列、店舗の列、売上金額の列だけ読み込む場合は次のように書きます。</p>

<pre class="line-numbers"><code class="language-python">sales_selected = pd.read_excel(
    &quot;sales_sample.xlsx&quot;,
    sheet_name=&quot;売上データ&quot;,
    usecols=[&quot;売上日&quot;, &quot;店舗&quot;, &quot;売上金額&quot;]
)

sales_selected
</code></pre>

  <div id="df-8b600d81-636d-43a7-b06b-83aeb804f815" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3000</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-8b600d81-636d-43a7-b06b-83aeb804f815')"
            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-8b600d81-636d-43a7-b06b-83aeb804f815 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-8b600d81-636d-43a7-b06b-83aeb804f815');
        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="id_7932c79f-7ef7-48ac-bd90-0408f06675ea">
    <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_selected')"
            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_7932c79f-7ef7-48ac-bd90-0408f06675ea button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<p><code>usecols</code> は「列を絞る」ための指定です。<br />
行を絞り込むための指定ではありません。</p>
<p>読み込んだあとに「東京店だけを見たい」「売上金額が1万円以上だけを見たい」という場合は、<code>read_excel()</code> ではなく、DataFrameの条件抽出で行います。</p>

<h2><span id="toc9">headerとskiprowsで見出し行のズレを調整する</span></h2>
<p>Excelファイルでは、1行目にタイトルや説明文があり、実際の表が2行目以降から始まることがあります。</p>
<p>たとえば、次のようなExcelです。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>Excel上の行</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">内容</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">1行目</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025年4月 売上レポート</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">2行目</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">※この行は説明行です。読み込み時には飛ばします。</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">3行目</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">売上日、店舗、商品、売上金額、数量</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">4行目以降</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">実際のデータ</td>
</tr>
</tbody>
</table>
<p>このようなファイルをそのまま読むと、表の列名が正しく読み込まれないことがあります。<br />
まずは、説明行ありのシートをそのまま確認してみます。</p>

<pre class="line-numbers"><code class="language-python">raw = pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=&quot;説明行あり&quot;, header=None)
raw.head(7)
</code></pre>

  <div id="df-c8a30a90-8997-4115-bf5c-754ec5c14c95" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">3</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025年4月 売上レポート</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
    </tr>
    <tr>
      <th style="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;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
    </tr>
    <tr>
      <th style="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;">店舗</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>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">3</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">4</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">5</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-c8a30a90-8997-4115-bf5c-754ec5c14c95')"
            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-c8a30a90-8997-4115-bf5c-754ec5c14c95 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-c8a30a90-8997-4115-bf5c-754ec5c14c95');
        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>上のように、表の前にタイトル行や説明行がある場合は、<code>header</code> または <code>skiprows</code> で調整します。</p>
<h3><span id="toc10">headerで「列名として使う行」を指定する</span></h3>
<p><code>header=2</code> と指定すると、0から数えて3行目を列名として使います。</p>

<pre class="line-numbers"><code class="language-python">df_header = pd.read_excel(
    &quot;sales_sample.xlsx&quot;,
    sheet_name=&quot;説明行あり&quot;,
    header=2
)

df_header
</code></pre>

  <div id="df-16a77fc5-812c-4d3d-82cb-29ba62587d7b" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-16a77fc5-812c-4d3d-82cb-29ba62587d7b')"
            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-16a77fc5-812c-4d3d-82cb-29ba62587d7b button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-16a77fc5-812c-4d3d-82cb-29ba62587d7b');
        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="id_f6fad9c1-684d-44e3-b3e4-139a0de64327">
    <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('df_header')"
            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_f6fad9c1-684d-44e3-b3e4-139a0de64327 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<h3><span id="toc11">skiprowsで「読み飛ばす行」を指定する</span></h3>
<p>同じ例では、先頭の2行を読み飛ばすために <code>skiprows=2</code> と書くこともできます。</p>

<pre class="line-numbers"><code class="language-python">df_skiprows = pd.read_excel(
    &quot;sales_sample.xlsx&quot;,
    sheet_name=&quot;説明行あり&quot;,
    skiprows=2
)

df_skiprows
</code></pre>

  <div id="df-eab2b5e4-214b-400a-89fc-ca040f1048dd" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-eab2b5e4-214b-400a-89fc-ca040f1048dd')"
            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-eab2b5e4-214b-400a-89fc-ca040f1048dd button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-eab2b5e4-214b-400a-89fc-ca040f1048dd');
        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="id_3838fbd7-4fdf-49b7-aa31-85534f73be75">
    <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('df_skiprows')"
            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_3838fbd7-4fdf-49b7-aa31-85534f73be75 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<p><code>header</code> と <code>skiprows</code> は似ていますが、考え方が少し違います。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>指定</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="white-space: nowrap; padding: 0.2em 0.4em;"><code>header</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="white-space: nowrap; padding: 0.2em 0.4em;"><code>skiprows</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>
<p>初心者のうちは、「見出し行を指定したいなら <code>header</code>」「不要な行を飛ばしたいなら <code>skiprows</code>」と考えると理解しやすいです。</p>
<p>処理前後のイメージは次のとおりです。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>状態</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="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="white-space: nowrap; padding: 0.2em 0.4em;"><code>header=2</code> または <code>skiprows=2</code> を指定する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>売上日</code>・<code>店舗</code>・<code>商品</code> などが列名になる</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">使いやすい</td>
</tr>
</tbody>
</table>

<h2><span id="toc12">index_colは必要な場合だけ使う</span></h2>
<p><code>index_col</code> は、特定の列をDataFrameのインデックスとして使うための引数です。</p>
<p>たとえば、売上日をインデックスにしたい場合は次のように書けます。</p>

<pre class="line-numbers"><code class="language-python">sales_index = pd.read_excel(
    &quot;sales_sample.xlsx&quot;,
    sheet_name=&quot;売上データ&quot;,
    index_col=&quot;売上日&quot;
)

sales_index
</code></pre>

  <div id="df-c5393f78-48c3-46e9-968c-52f58a4f1492" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="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="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</th>
      <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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</th>
      <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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-c5393f78-48c3-46e9-968c-52f58a4f1492')"
            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-c5393f78-48c3-46e9-968c-52f58a4f1492 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-c5393f78-48c3-46e9-968c-52f58a4f1492');
        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="id_e8438838-4637-4e48-917b-691bff9092e9">
    <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_index')"
            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_e8438838-4637-4e48-917b-691bff9092e9 button.colab-df-generate');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

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

    </div>
  </div>

<p>ただし、初心者のうちは <code>index_col</code> を無理に使う必要はありません。</p>
<p>普通の列として残しておいたほうが、あとから <code>to_datetime()</code> で日付型に変換したり、条件抽出したりしやすいことも多いです。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>状況</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">おすすめ</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">まずDataFrameの中身を確認したい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>index_col</code> は指定しない</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">IDや日付を行ラベルとして使いたい理由がある</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>index_col</code> を検討する</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">インデックスにして迷った</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>reset_index()</code> で列に戻す</td>
</tr>
</tbody>
</table>
<p>インデックスにした列を戻したい場合は、<code>reset_index()</code> が使えます。</p>

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

  <div id="df-081686e4-5195-483d-b430-12efa008b585" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-081686e4-5195-483d-b430-12efa008b585')"
            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-081686e4-5195-483d-b430-12efa008b585 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-081686e4-5195-483d-b430-12efa008b585');
        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="toc13">read_excel()とread_csv()の違い</span></h2>
<p>pandasで外部ファイルを読み込む代表的な関数に、<code>read_excel()</code> と <code>read_csv()</code> があります。</p>
<p>どちらもDataFrameを作るための関数ですが、対象ファイルが違います。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>比較項目</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>read_excel()</code></th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>read_csv()</code></th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">対象ファイル</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">Excelファイル</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVファイル</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">代表的な拡張子</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.xlsx</code>, <code>.xls</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.csv</code></td>
</tr>
<tr>
  <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="white-space: nowrap; padding: 0.2em 0.4em;">よく使う引数</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>sheet_name</code>, <code>usecols</code>, <code>header</code>, <code>skiprows</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>encoding</code>, <code>sep</code>, <code>usecols</code>, <code>header</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">使う場面</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">Excelで配布された表を読む</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVとして保存されたデータを読む</td>
</tr>
</tbody>
</table>
<p>CSVファイルを読み込む場合は、<code>pd.read_csv()</code> を使います。<br />
Excelファイルを読み込む場合は、<code>pd.read_excel()</code> を使います。</p>
<p>ここを混同すると、ファイルがうまく読めない原因になります。</p>

<h2><span id="toc14">ExcelをCSVに変換してから扱ったほうがよい場合</span></h2>
<p>Excelファイルをpandasで読み込んだあと、毎回同じデータを分析するなら、CSVに変換して保存しておくと扱いやすくなります。</p>
<p>Excelは、複数シート、装飾、結合セル、説明行などを含められるため、人が見る資料としては便利です。<br />
一方で、pandasで分析するデータとしては、1つの表に整理されたCSVのほうがシンプルです。</p>
<p>おすすめの流れは次のとおりです。</p>
<ol>
<li><code>read_excel()</code> でExcelファイルを読み込む</li>
<li><code>head()</code>・<code>info()</code> で中身を確認する</li>
<li>必要なシート・列・見出し行を整える</li>
<li>分析しやすいDataFrameになったらCSVとして保存する</li>
<li>次回以降は <code>read_csv()</code> で読み込む</li>
</ol>
<p>判断基準を整理すると、次のようになります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>状況</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">おすすめ</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">Excelの中身を初めて確認する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>read_excel()</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">複数シートから必要な表を選びたい</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>read_excel()</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">毎回同じ整った表を分析する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVに変換して <code>read_csv()</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">装飾や結合セルが多いExcel</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">必要な表だけ読み込み、CSV化を検討する</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">人に配る資料として使う</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">Excelのまま</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">pandasで繰り返し分析する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVのほうが扱いやすい</td>
</tr>
</tbody>
</table>
<p>ただし、この記事の主役はあくまで <code>read_excel()</code> です。<br />
CSV保存の細かい設定には深入りせず、「読み込んで整えたDataFrameを、必要に応じてCSVに保存できる」と理解しておけば十分です。</p>

<pre class="line-numbers"><code class="language-python">df = pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=&quot;売上データ&quot;)

# 分析しやすい形になったDataFrameをCSVとして保存する
df.to_csv(&quot;sales_sample.csv&quot;, index=False)
</code></pre>

<p>保存したCSVは、次回以降 <code>read_csv()</code> で読み込めます。<br />
同じ整った表を繰り返し分析する場合は、この形にしておくと扱いやすくなります。</p>

<pre class="line-numbers"><code class="language-python">df_csv = pd.read_csv(&quot;sales_sample.csv&quot;)
df_csv.head()
</code></pre>

  <div id="df-444e5b5f-5606-4bb3-bae5-e7731fd0881c" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-444e5b5f-5606-4bb3-bae5-e7731fd0881c')"
            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-444e5b5f-5606-4bb3-bae5-e7731fd0881c button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-444e5b5f-5606-4bb3-bae5-e7731fd0881c');
        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="toc15">よくあるミスとエラー対処</span></h2>
<p>Excelファイルの読み込みでは、初心者がつまずきやすいポイントがあります。</p>
<h3><span id="toc16">read_csv()でExcelファイルを読もうとしてしまう</span></h3>
<p>Excelファイルは、基本的に <code>read_csv()</code> では読み込みません。</p>
<pre><code class="language-python">pd.read_csv(&quot;sales_sample.xlsx&quot;)
</code></pre>
<p>このように書くと、Excelファイルの形式とCSVの形式が違うため、うまく読み込めません。<br />
Excelファイルには <code>read_excel()</code> を使いましょう。</p>
<h3><span id="toc17">sheet_nameを列名だと思ってしまう</span></h3>
<p><code>sheet_name</code> は、Excelのシート名を指定するための引数です。<br />
読み込む列を指定したい場合は、<code>usecols</code> を使います。</p>
<h3><span id="toc18">usecolsで行を絞ろうとしてしまう</span></h3>
<p><code>usecols</code> は列を絞るための引数です。<br />
行を絞りたい場合は、読み込んだあとに条件抽出を使います。</p>
<h3><span id="toc19">openpyxlが必要というエラーが出る</span></h3>
<p>環境によっては、Excelファイルを読み込むときに <code>openpyxl</code> が必要になることがあります。<br />
Google Colabでは使えることが多いですが、エラーが出る場合は次のようにインストールします。</p>

<pre class="line-numbers"><code class="language-python"># openpyxlが必要というエラーが出る場合のみ実行します
# Google Colabでは、すでに使える場合もあります

# !pip install openpyxl
</code></pre>

<p>このエラーは、pandasのコードの書き方が間違っているというより、Excelを読み込むためのエンジンが環境に不足している場合に起きます。</p>

<h2><span id="toc20">読み込んだ後は前処理につなげる</span></h2>
<p><code>read_excel()</code> は、ExcelファイルをDataFrameにする入口です。<br />
読み込んだあとは、データ分析しやすい形になっているかを確認します。</p>
<p>たとえば、次のような流れです。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>確認・前処理</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="white-space: nowrap; padding: 0.2em 0.4em;">先頭を確認</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>head()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">読み込み結果を見る</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">型・欠損値を確認</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>info()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付・数値・欠損を確認する</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列名を整える</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>rename()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">日本語列名や長い列名を扱いやすくする</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付型に変換</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>to_datetime()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付として扱えるようにする</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">数値・文字列に変換</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>astype()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">分析に合う型にする</td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">欠損値を確認・処理</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>isnull()</code>・<code>fillna()</code></td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">空欄を把握して補う</td>
</tr>
</tbody>
</table>
<p>次の例では、Excelから読み込んだ売上データの列名を少し短くし、売上日を日付型に変換します。</p>

<pre class="line-numbers"><code class="language-python">sales_clean = pd.read_excel(&quot;sales_sample.xlsx&quot;, sheet_name=&quot;売上データ&quot;)

# 列名を扱いやすくする
sales_clean = sales_clean.rename(columns={
    &quot;売上金額&quot;: &quot;金額&quot;
})

# 売上日を日付型に変換する
sales_clean[&quot;売上日&quot;] = pd.to_datetime(sales_clean[&quot;売上日&quot;])

sales_clean.head()
</code></pre>

  <div id="df-c6dd5a2d-4a19-4a7d-91b4-ed2c793ef753" 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 border="1" class="dataframe wp-block-table">
  <thead style="white-space: nowrap; padding: 0.2em 0.4em;">
    <tr style="text-align: right;">
      <th></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="white-space: nowrap; padding: 0.2em 0.4em;">0</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">東京店</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">1</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-02</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;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
    </tr>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">2</th>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2025-04-03</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>
</div>
    <div class="colab-df-buttons">

  <div class="colab-df-container">
    <button class="colab-df-convert" onclick="convertToInteractive('df-c6dd5a2d-4a19-4a7d-91b4-ed2c793ef753')"
            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-c6dd5a2d-4a19-4a7d-91b4-ed2c793ef753 button.colab-df-convert');
      buttonEl.style.display =
        google.colab.kernel.accessAllowed ? 'block' : 'none';

      async function convertToInteractive(key) {
        const element = document.querySelector('#df-c6dd5a2d-4a19-4a7d-91b4-ed2c793ef753');
        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>

<pre class="line-numbers"><code class="language-python">sales_clean.info()
</code></pre>

<pre>&lt;class &#x27;pandas.core.frame.DataFrame&#x27;&gt;
RangeIndex: 3 entries, 0 to 2
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   売上日     3 non-null      datetime64[ns]
 1   店舗      3 non-null      object        
 2   商品      3 non-null      object        
 3   金額      3 non-null      int64         
 4   数量      3 non-null      int64         
dtypes: datetime64[ns](1), int64(2), object(2)
memory usage: 252.0+ bytes
</pre>

<p>このように、Excelファイルを読み込んだら、次はDataFrameの確認と前処理に進みます。</p>
<p><code>read_excel()</code> の役割は、ExcelをDataFrameに変えることです。<br />
そのあとの列名変更、型変換、日付変換、欠損値処理は、それぞれ別の前処理として考えると整理しやすくなります。</p>

<h2><span id="toc21">read_excel()で押さえるポイントを整理する</span></h2>
<p>ここまでで、ExcelファイルをDataFrameとして読み込む基本を確認しました。</p>
<p><code>read_excel()</code> では、まず基本形で読み込み、必要に応じて引数を追加していくと迷いにくくなります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead style="white-space: nowrap; padding: 0.2em 0.4em;">
<tr>
  <th>目的</th>
  <th style="white-space: nowrap; padding: 0.2em 0.4em;">使うもの</th>
</tr>
</thead>
<tbody>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">Excelファイルを読み込む</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>pd.read_excel()</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">シートを指定する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>sheet_name</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">必要な列だけ読む</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>usecols</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">見出し行を調整する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>header</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">不要な説明行を飛ばす</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>skiprows</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">行ラベルにする列を指定する</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>index_col</code></td>
</tr>
<tr>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;">列名を自分で付ける</td>
  <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>names</code></td>
</tr>
</tbody>
</table>
<p>最初からすべての引数を覚える必要はありません。<br />
まずは <code>pd.read_excel(&quot;ファイル名.xlsx&quot;)</code> で読み込み、<code>head()</code> と <code>info()</code> で確認し、必要なところだけ調整していきましょう。</p>
<p>読み込んだ後は、列名変更・型変換・日付変換・欠損値処理などの前処理を行い、条件抽出・集計・可視化へ進みます。</p>

<h2><span id="toc22">まとめ</span></h2>
<p>この記事では、pandasの <code>read_excel()</code> を使ってExcelファイルを読み込む方法を解説しました。</p>
<p>重要なポイントを整理します。</p>
<ul>
<li>Excelファイルを読み込むには <code>pd.read_excel(&quot;ファイル名.xlsx&quot;)</code> を使う</li>
<li>複数シートから読み込む場合は <code>sheet_name</code> を使う</li>
<li>必要な列だけ読み込む場合は <code>usecols</code> を使う</li>
<li>見出し行がずれている場合は <code>header</code> を使う</li>
<li>表の上に説明行がある場合は <code>skiprows</code> を使う</li>
<li><code>index_col</code> は必要な場合だけ使う</li>
<li>CSVファイルは <code>read_csv()</code>、Excelファイルは <code>read_excel()</code> と使い分ける</li>
<li>読み込んだあとは <code>head()</code>・<code>info()</code>・<code>describe()</code> で確認する</li>
<li>その後、列名変更・型変換・日付変換・欠損値処理へ進む</li>
<li>毎回同じ整った表を分析するなら、必要に応じてCSVに保存しておくと、次回以降は <code>read_csv()</code> で扱いやすい</li>
</ul>
<p>まずは、シンプルなExcelファイルを <code>read_excel()</code> で読み込み、<code>head()</code> と <code>info()</code> で確認するところから始めるのがおすすめです。</p>

<h2><span id="toc23">次に読みたい関連記事</span></h2>
<p>Excelファイルを読み込んだあとは、DataFrameの確認や前処理へ進むと理解が深まります。</p>
<ul>
<li><p><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門</a><br />
CSVファイルの読み込みやGoogle Drive連携を確認したい場合におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a><br />
読み込んだ表がDataFrameとしてどう扱われるかを理解したい場合に役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-head/">Pandas head()の使い方</a><br />
読み込んだデータの先頭を確認する基本操作を学べます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い</a><br />
型・欠損値・統計量の確認方法を整理できます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-rename/">pandas rename()の使い方</a><br />
Excelから読み込んだ列名を整えたいときに役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方</a><br />
数値や文字列の型を整えたいときに使います。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方</a><br />
Excelの日付列を日付型として扱いたいときにおすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方</a><br />
Excelの空欄や欠損値を処理したいときに役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-reset-index/">pandas reset_index()の使い方</a><br />
<code>index_col</code> で指定した列を戻したいときに参考になります。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-concat/">Pandas concat完全ガイド</a><br />
複数のファイルや複数のDataFrameを結合したい場合に役立ちます。</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="toc24"> カテゴリから探す</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>

</div>



<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1777995171883" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc25">pandasでExcelファイルを読み込むにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p><code>pd.read_excel("ファイル名.xlsx")</code> を使います。<br />まずはこの基本形で読み込み、必要に応じて <code>sheet_name</code>・<code>usecols</code>・<code>header</code>・<code>skiprows</code> を指定します。</p>

</div>
</div>
<div id="faq-question-1777995190194" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">read_excel()とread_csv()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>read_excel()</code> はExcelファイルを読み込む関数で、主に <code>.xlsx</code> や <code>.xls</code> を扱います。<br /><code>read_csv()</code> はCSVファイルを読み込む関数で、主に <code>.csv</code> を扱います。<br />Excelファイルを読む場合は <code>read_excel()</code>、CSVファイルを読む場合は <code>read_csv()</code> と使い分けます。</p>

</div>
</div>
<div id="faq-question-1777995230165" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">Excelの複数シートを読み込むにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>特定のシートを読み込む場合は、<code>sheet_name</code> を使います。<br /><code>pd.read_excel("sales_sample.xlsx", sheet_name="売上データ")</code></p>
<p>複数シートをまとめて読み込む方法もありますが、初心者のうちはまず必要なシートを1つずつ指定して読むのがおすすめです。</p>

</div>
</div>
<div id="faq-question-1777995255834" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">特定の列だけ読み込むにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p><code>usecols</code> を使います。<br /><code>pd.read_excel("sales_sample.xlsx", usecols=["売上日", "店舗", "売上金額"])</code></p>
<p><code>usecols</code> は列を絞るための指定です。<br />行を絞りたい場合は、読み込んだあとに条件抽出を使います。</p>

</div>
</div>
<div id="faq-question-1777995271290" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc29">1行目が見出しではないExcelはどう読み込めばよいですか？</span></h3>
<div class="rank-math-answer ">

<p>見出し行が何行目にあるか分かっている場合は、<code>header</code> を使います。<br />たとえば、3行目を見出しにしたい場合は <code>header=2</code> と指定します。<br /><code>pd.read_excel("sales_sample.xlsx", header=2)</code></p>
<p>先頭の説明行を読み飛ばしたい場合は、<code>skiprows</code> を使うこともあります。</p>

</div>
</div>
<div id="faq-question-1777995288745" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">列名を自分で付けたい場合はどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>Excelに見出し行がない場合や、読み込み時に列名を自分で指定したい場合は、<code>names</code> を使う方法があります。<br /><code>pd.read_excel("sales_sample.xlsx", header=None, names=["売上日", "店舗","商品", "売上金額", "数量"])</code></p>
<p>ただし、初心者のうちは、まず <code>header</code> で見出し行を正しく読み込む方法を覚えるのがおすすめです。<br />読み込んだあとに列名を整えたい場合は、<code>rename()</code> を使うと流れがわかりやすくなります。</p>

</div>
</div>
<div id="faq-question-1777995338234" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">openpyxlが必要というエラーが出たらどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>環境にExcel読み込み用のエンジンが不足している可能性があります。<br />Google Colabでは最初から使えることも多いですが、ローカル環境や一部の環境でエラーが出る場合は、必要に応じて次のようにインストールします。<br /><code>!pip install openpyxl</code></p>
<p>インストール後は、ランタイムやノートブックを再実行すると読み込めることがあります。</p>

</div>
</div>
<div id="faq-question-1777995346786" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">読み込んだExcelの日付や数値の型がおかしいときはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>まず <code>info()</code> で列の型を確認します。<br />日付列が文字列として読み込まれている場合は <code>pd.to_datetime()</code>、数値や文字列の型を整えたい場合は <code>astype()</code> を使います。</p>

</div>
</div>
<div id="faq-question-1777995371634" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">Excelに保存するにはto_excel()を使えばよいですか？</span></h3>
<div class="rank-math-answer ">

<p>はい。DataFrameをExcelファイルとして保存する場合は <code>to_excel()</code> を使います。<br />ただし、この記事の中心は読み込み用の <code>read_excel()</code> です。<br />保存については、まず「読み込み」と「前処理」の流れに慣れてから学ぶと理解しやすいです。</p>

</div>
</div>
<div id="faq-question-1777995386434" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">ExcelはCSVに変換してから扱ったほうがよいですか？</span></h3>
<div class="rank-math-answer ">

<p>繰り返し同じ表を分析するなら、CSVに変換しておくと扱いやすいことが多いです。<br />Excelは人が見る資料として便利ですが、pandasで繰り返し分析するなら、1つの表に整理されたCSVのほうがシンプルです。<br />ただし、複数シートから必要な表を選ぶ段階では <code>read_excel()</code> が便利です。<br />まず <code>read_excel()</code> で読み込み、必要なシート・列・見出し行を整えたあと、必要に応じて <code>to_csv()</code> で保存するとよいです。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-read-excel/">pandas read_excel()の使い方｜Excelファイル読み込み・sheet_name・usecolsを解説</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-read-excel/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas unique()とnunique()の使い方｜値の一覧・種類数・value_counts()との違いを解説</title>
		<link>https://pythondatalab.com/pandas-unique-nunique/</link>
					<comments>https://pythondatalab.com/pandas-unique-nunique/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Tue, 05 May 2026 10:52:32 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2044</guid>

					<description><![CDATA[<p>pandasのunique()とnunique()の違いを初心者向けに解説。値の一覧を確認するunique()、種類数を数えるnunique()、value_counts()との使い分け、欠損値や表記ゆれ確認の注意点まで具体例で紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-unique-nunique/">pandas unique()とnunique()の使い方｜値の一覧・種類数・value_counts()との違いを解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[


<link href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism-tomorrow.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/toolbar/prism-toolbar.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.css" rel="stylesheet"/>
<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 {
    line-height: 1.85;
  }
  .colab-article pre[class*="language-"] {
    margin: 0 !important;
    padding: 1em;
  }
  .colab-article pre.line-numbers {
    margin: 0 !important;
  }
  .colab-article .colab-cell-output {
    margin: 0.6em 0 1.2em;
  }
  .colab-article .colab-output {
    margin: 0 !important;
    padding: 0.8em 1em;
    background: #f7f7f7;
    border: 1px solid #e5e7eb;
    overflow-x: auto;
    white-space: pre;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 1em 0;
  }
  .colab-article table.wp-block-table th,
  .colab-article table.wp-block-table td {
    white-space: nowrap;
    padding: 0.2em 0.4em;
    border: 1px solid #ddd;
  }
  .colab-article table.wp-block-table th:first-child,
  .colab-article table.wp-block-table td:first-child {
    min-width: 3em;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }


  /* 横長の表が本文幅を超える場合は、サイドバーへはみ出さず横スクロールにする */
  .colab-article .pdl-table-scroll {
    max-width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    margin: 1em 0;
  }
  .colab-article .pdl-table-scroll table.wp-block-table {
    margin: 0;
  }
  .colab-article table.wp-block-table {
    max-width: 100%;
  }
</style>
<div class="colab-article" style="max-width: 100%;">
<p>CSVを読み込んだあと、<code>部署</code>、<code>商品カテゴリ</code>、<code>ステータス</code> のような列を見て、次のように感じることがあります。</p>
<p>「この列には、どんな値が入っているのだろう？」<br/>
「カテゴリの種類はいくつあるのだろう？」<br/>
「<code>unique()</code>、<code>nunique()</code>、<code>value_counts()</code> のどれを使えばよいのだろう？」</p>
<p>このようなときに役立つのが、Pandasの <code>unique()</code> と <code>nunique()</code> です。</p>
<p>最初に結論を言うと、<strong>値の一覧を見たいときは <code>unique()</code>、値の種類数だけ知りたいときは <code>nunique()</code>、値ごとの件数まで見たいときは <code>value_counts()</code></strong> を使います。</p>
<p>この記事では、<code>unique()</code> と <code>nunique()</code> の違い、欠損値の扱い、<code>value_counts()</code> との使い分け、表記ゆれを見つける流れを、Google Colabで試しやすい例で解説します。</p>
<p>特に、集計やグラフ化をする前にカテゴリ列の中身を確認しておくと、表記ゆれや欠損値に早く気づけます。</p>
<h2><span id="toc1">先に結論：3つのメソッドは目的で使い分ける</span></h2>
<p><code>unique()</code>、<code>nunique()</code>、<code>value_counts()</code> は、どれも列の値を確認するときに使います。<br/>
ただし、見たいものが違います。</p>
<div class="pdl-point-box" style="border: 2px solid #dbeafe; background: #f8fbff; padding: 1em; border-radius: 10px; margin: 1.2em 0;">
<p style="font-weight: 700; margin-top: 0;">迷ったら、まずはこの基準で選びます。</p>
<div class="pdl-table-scroll" style="overflow-x: auto; max-width: 100%;">
<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;"><code>unique()</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;">種類数だけ知りたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>nunique()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4種類</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;"><code>value_counts()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">営業部が3件、企画部が2件</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>この記事では、この使い分けを実際のDataFrameで確認していきます。</p>
<h2><span id="toc2">この記事でわかること</span></h2>
<p>この記事では、次の内容を扱います。</p>
<ul>
<li><code>unique()</code> で重複を除いた値の一覧を確認する方法</li>
<li><code>nunique()</code> で値の種類数を確認する方法</li>
<li><code>unique()</code> と <code>nunique()</code> の違い</li>
<li><code>value_counts()</code> との使い分け</li>
<li>欠損値がある場合の注意点</li>
<li><code>count()</code> と <code>nunique()</code> の違い</li>
<li>表記ゆれ確認での使い方</li>
<li><code>groupby().nunique()</code> でグループごとの種類数を確認する考え方</li>
</ul>
<p>この記事のゴールは、<code>unique()</code>・<code>nunique()</code>・<code>value_counts()</code> の違いを理解し、データの中身確認から表記ゆれ・欠損値・集計前の前処理へ進めるようになることです。</p>
<h2><span id="toc3">似たメソッドまで含めた使い分け</span></h2>
<p>基本は、上の3つを押さえれば十分です。<br/>
ここでは、実務で一緒に迷いやすい <code>groupby().nunique()</code> や <code>duplicated()</code> も含めて、少しだけ整理しておきます。</p>
<div class="pdl-table-scroll"><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;"><code>unique()</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;">値の種類数だけ知りたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>nunique()</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;">値ごとの件数まで知りたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>value_counts()</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;">グループごとに種類数を知りたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>groupby().nunique()</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;">重複している行そのものを確認したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>duplicated()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">同じ注文行が重複していないか確認する</td>
</tr>
</tbody>
</table></div>
<p><code>unique()</code> と <code>nunique()</code> は、どちらも「重複を除いた値」に関係します。</p>
<p>ただし、返すものが違います。</p>
<div class="pdl-table-scroll"><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>unique()</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>nunique()</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></div>
<p>たとえば、<code>部署</code> の中身を見て「営業部」と「営業」が混ざっていないか確認したいなら <code>unique()</code> が向いています。</p>
<p>一方で、部署が何種類あるかだけ知りたいなら <code>nunique()</code> が向いています。</p>
<p>このあと、まずは主役である <code>unique()</code> と <code>nunique()</code> を実際のDataFrameで確認し、その後で <code>value_counts()</code> や欠損値の扱いとの違いを見ていきます。</p>
<h2><span id="toc4">サンプルデータを用意する</span></h2>
<p>ここでは、売上データを例にします。</p>
<p><code>部署</code>、<code>商品カテゴリ</code>、<code>ステータス</code> のようなカテゴリ列を含むDataFrameです。実際のCSVを読み込んだあとにも、同じような確認をすることがよくあります。</p>
<p>このサンプルでは、欠損値を <code>pd.NA</code> で入れています。実際のデータでは、表示上 <code>NaN</code> や <code>&lt;NA&gt;</code> と出ることがありますが、どちらも「値が入っていない状態」として扱います。</p>
<pre class="line-numbers"><code class="language-python">import pandas as pd


df = pd.DataFrame({
    "注文ID": [101, 102, 103, 104, 105, 106, 107, 108],
    "部署": ["営業部", "営業部", "企画部", "営業", "人事部", "企画部", "営業部", pd.NA],
    "商品カテゴリ": ["PC", "マウス", "PC", "キーボード", "マウス", "PC", "モニター", "PC"],
    "ステータス": ["完了", "完了", "処理中", "完了", "キャンセル", "処理中", "完了", pd.NA],
    "売上": [120000, 3000, 150000, 8000, 2500, 140000, 32000, 110000]
})


df</code></pre>
<div class="colab-cell-output">
<div class="pdl-table-scroll"><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;">注文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><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;">101</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">営業部</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;">120000</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;">102</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><td style="white-space: nowrap; padding: 0.2em 0.4em;">3000</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;">103</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">企画部</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;">150000</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;">104</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><td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">105</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><td style="white-space: nowrap; padding: 0.2em 0.4em;">2500</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;">106</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">企画部</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;">140000</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;">107</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><td style="white-space: nowrap; padding: 0.2em 0.4em;">32000</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;">108</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">&lt;NA&gt;</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">PC</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">&lt;NA&gt;</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">110000</td></tr></tbody></table></div>
</div>
<p>このデータでは、<code>部署</code> 列に <code>営業部</code> と <code>営業</code> が混ざっています。</p>
<p>これは、同じ意味の値が別表記で入っている「表記ゆれ」の可能性があります。<br/>
このような状態を見つけるためにも、<code>unique()</code> は役立ちます。</p>
<h2><span id="toc5">unique()で重複を除いた値の一覧を確認する</span></h2>
<p><code>unique()</code> は、列に含まれる値を重複なしで確認するメソッドです。</p>
<p>まずは、<code>部署</code> 列に入っている値を一覧で確認します。<br/>
この結果を見ることで、表記ゆれや欠損値の有無に気づきやすくなります。</p>
<pre class="line-numbers"><code class="language-python">df["部署"].unique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>array(['営業部', '企画部', '営業', '人事部', &lt;NA&gt;], dtype=object)</code></pre>
</div>
<p><code>unique()</code> を使うと、<code>部署</code> 列に含まれる値の一覧を確認できます。</p>
<p>この結果を見ると、<code>営業部</code> と <code>営業</code> が別の値として入っていることがわかります。<br/>
実際には同じ意味で入力されているなら、あとで <code>replace()</code> などを使って表記をそろえる候補になります。</p>
<p>ここで大事なのは、<code>unique()</code> は<strong>元のDataFrameを書き換える処理ではない</strong>という点です。<br/>
あくまで、列の中にどんな値があるかを確認するためのメソッドです。</p>
<p>下の表では、実際の出力をそのまま貼るのではなく、初心者が読み取りやすいように値の部分だけを整理して示しています。</p>
<div class="pdl-table-scroll"><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;"><code>unique()</code>で見える値</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>部署</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>営業部</code>, <code>企画部</code>, <code>営業</code>, <code>人事部</code>, <code>&lt;NA&gt;</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>営業部</code> と <code>営業</code> が表記ゆれの可能性</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>ステータス</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>完了</code>, <code>処理中</code>, <code>キャンセル</code>, <code>&lt;NA&gt;</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>商品カテゴリ</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>PC</code>, <code>マウス</code>, <code>キーボード</code>, <code>モニター</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">どの商品カテゴリがあるか確認できる</td>
</tr>
</tbody>
</table></div>
<p>このように、<code>unique()</code> は「集計する前に、列の中身をざっと確認する」場面で便利です。</p>
<p>特に、Colab上では <code>array([...], dtype=object)</code> のように表示されることがあります。<br/>
これは「値の一覧が配列の形で返っている」という意味なので、初心者のうちは次のように読み替えると十分です。</p>
<div class="pdl-table-scroll"><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;">Colabで出る表示の一部</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>array([...], dtype=object)</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>営業部</code>, <code>企画部</code>, <code>営業</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>部署</code> 列に入っている値</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>&lt;NA&gt;</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>dtype=object</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">文字列などを含む列として扱われている</td>
</tr>
</tbody>
</table></div>
<p>ここでは、<code>dtype=object</code> の細かい意味まで深掘りしなくて大丈夫です。<br/>
まずは「どんな値が入っているかを確認できた」と考えれば問題ありません。</p>
<h3><span id="toc6">unique()の結果はDataFrameではない</span></h3>
<p><code>unique()</code> の戻り値は、通常のDataFrameではなく、配列のような形で返ってきます。</p>
<p>そのため、表として整えて見たい場合は、必要に応じて <code>pd.Series()</code> に変換して確認することもできます。</p>
<pre class="line-numbers"><code class="language-python">pd.Series(df["部署"].unique(), name="部署の値")</code></pre>
<div class="colab-cell-output">
<div class="pdl-table-scroll"><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;">0</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></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></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></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;">&lt;NA&gt;</td></tr></tbody></table></div>
</div>
<p>このようにすると、値の一覧を縦に並べて確認しやすくなります。</p>
<p>ただし、普段の確認では <code>df["列名"].unique()</code> だけでも十分なことが多いです。</p>
<h2><span id="toc7">nunique()で値の種類数を確認する</span></h2>
<p><code>nunique()</code> は、重複を除いた値の「個数」を数えるメソッドです。</p>
<p><code>unique()</code> が「どんな値があるか」を見るのに対して、<code>nunique()</code> は「何種類あるか」を確認します。</p>
<p>次に、値そのものではなく「何種類あるか」だけを確認します。<br/>
このときに使うのが <code>nunique()</code> です。</p>
<pre class="line-numbers"><code class="language-python">df["部署"].nunique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>4</code></pre>
</div>
<p>この結果は、<code>部署</code> 列に含まれる欠損値を除いた種類数です。</p>
<p>ここで注意したいのは、<code>nunique()</code> は標準では欠損値を数えないことです。<br/>
欠損値も1種類として数えたい場合は、<code>dropna=False</code> を指定します。</p>
<pre class="line-numbers"><code class="language-python">df["部署"].nunique(dropna=False)</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>5</code></pre>
</div>
<p>欠損値を含めて種類数を見たい場合は、<code>dropna=False</code> を使います。</p>
<div class="pdl-table-scroll"><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;"><code>df["部署"].nunique()</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;">欠損値も含めて種類数を数える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>df["部署"].nunique(dropna=False)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">数える</td>
</tr>
</tbody>
</table></div>
<p>データ確認の段階では、まず標準の <code>nunique()</code> で種類数を見て、欠損値も気になる場合に <code>dropna=False</code> を使うと考えるとわかりやすいです。</p>
<h2><span id="toc8">unique()とnunique()の違い</span></h2>
<p><code>unique()</code> と <code>nunique()</code> は名前が似ていますが、目的は違います。</p>
<div class="pdl-table-scroll"><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;"><code>unique()</code></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>nunique()</code></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>
<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>
<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>
<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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">標準では欠損値を数えない</td>
</tr>
</tbody>
</table></div>
<p>たとえば、<code>部署</code> の中身を見て「営業部」と「営業」が混ざっていないか確認したいなら <code>unique()</code> が向いています。</p>
<p>一方で、部署が何種類あるかだけ知りたいなら <code>nunique()</code> が向いています。</p>
<h2><span id="toc9">value_counts()との違い</span></h2>
<p><code>unique()</code> や <code>nunique()</code> と一緒に迷いやすいのが、<code>value_counts()</code> です。</p>
<p><code>value_counts()</code> は、値ごとの件数を数えるメソッドです。</p>
<p>値ごとの件数まで見たい場合は、<code>unique()</code> ではなく <code>value_counts()</code> を使います。</p>
<pre class="line-numbers"><code class="language-python">df["部署"].value_counts(dropna=False)</code></pre>
<div class="colab-cell-output">
<div class="pdl-table-scroll"><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;">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><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;">&lt;NA&gt;</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td></tr></tbody></table></div>
</div>
<p><code>value_counts()</code> を使うと、値の一覧だけでなく、それぞれの値が何件あるかまで確認できます。</p>
<div class="pdl-table-scroll"><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;"><code>unique()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>営業部</code>, <code>企画部</code>, <code>営業</code>, <code>人事部</code>, <code>&lt;NA&gt;</code></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;"><code>nunique()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>4</code> など</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;"><code>value_counts()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>営業部: 3件</code>, <code>企画部: 2件</code> など</td>
</tr>
</tbody>
</table></div>
<p><code>value_counts()</code> はとても便利ですが、この記事では詳しく深掘りしません。<br/>
件数集計や割合表示まで確認したい場合は、<code>value_counts()</code> の記事に進むと理解しやすくなります。</p>
<p>関連記事：<br/>
<a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></p>
<h2><span id="toc10">欠損値（NaN / &lt;NA&gt;）がある場合の注意点</span></h2>
<p><code>unique()</code> と <code>nunique()</code> では、欠損値の扱いが少し違います。</p>
<p>このサンプルでは <code>pd.NA</code> を使っているため、実行結果では <code>&lt;NA&gt;</code> と表示されます。<br/>
CSVから読み込んだデータでは <code>NaN</code> と表示されることもありますが、ここではどちらも「欠損値」として考えます。</p>
<p><code>ステータス</code> 列で確認してみましょう。</p>
<pre class="line-numbers"><code class="language-python">df["ステータス"].unique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>array(['完了', '処理中', 'キャンセル', &lt;NA&gt;], dtype=object)</code></pre>
</div>
<pre class="line-numbers"><code class="language-python">df["ステータス"].nunique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>3</code></pre>
</div>
<pre class="line-numbers"><code class="language-python">df["ステータス"].nunique(dropna=False)</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>4</code></pre>
</div>
<p>結果を見ると、<code>unique()</code> では欠損値が結果に出ることがあります。<br/>
一方で、<code>nunique()</code> は標準では欠損値を数えません。</p>
<div class="pdl-table-scroll"><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>unique()</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>nunique()</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>nunique(dropna=False)</code></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;"><code>value_counts(dropna=False)</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">欠損値の件数も表示できる</td>
</tr>
</tbody>
</table></div>
<p>欠損値そのものを詳しく確認したい場合は、<code>isnull()</code> や <code>fillna()</code> とあわせて考えるとよいです。</p>
<p>関連記事：<br/>
<a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></p>
<h2><span id="toc11">count()とnunique()の違い</span></h2>
<p>ここは補足です。<br/>
<code>nunique()</code> と似て見えやすいものに、<code>count()</code> があります。</p>
<p><code>count()</code> は、欠損値以外のデータ数を数えるメソッドです。<br/>
一方、<code>nunique()</code> は、重複を除いた値の種類数を数えます。</p>
<p>同じ <code>部署</code> 列で、結果の違いだけ確認しておきましょう。</p>
<pre class="line-numbers"><code class="language-python">pd.DataFrame({
    "確認内容": ["欠損値以外の件数", "値の種類数"],
    "使うメソッド": ["count()", "nunique()"],
    "結果": [df["部署"].count(), df["部署"].nunique()]
})</code></pre>
<div class="colab-cell-output">
<div class="pdl-table-scroll"><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;">0</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">欠損値以外の件数</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">count()</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">7</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;">nunique()</td><td style="white-space: nowrap; padding: 0.2em 0.4em;">4</td></tr></tbody></table></div>
</div>
<p><code>count()</code> は、<code>部署</code> に値が入っている行数を数えます。<br/>
<code>nunique()</code> は、<code>部署</code> に何種類の値があるかを数えます。</p>
<p>つまり、同じ「数える」でも、見ているものが違います。</p>
<div class="pdl-table-scroll"><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>count()</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>nunique()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">重複を除いた値の種類数</td>
</tr>
</tbody>
</table></div>
<p>カテゴリ列の中身を確認したい場合は、<code>unique()</code> や <code>nunique()</code> の方が目的に合いやすいです。</p>
<h2><span id="toc12">unique()で表記ゆれを見つける</span></h2>
<p><code>unique()</code> は、表記ゆれを見つけるときにも役立ちます。</p>
<p>表記ゆれとは、同じ意味の値が少し違う表記で入っている状態です。</p>
<p>たとえば、今回の <code>部署</code> 列には、次のような値があります。</p>
<pre class="line-numbers"><code class="language-python">df["部署"].unique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>array(['営業部', '企画部', '営業', '人事部', &lt;NA&gt;], dtype=object)</code></pre>
</div>
<p>この結果を見ると、<code>営業部</code> と <code>営業</code> が別の値として扱われています。</p>
<p>もしこの2つが同じ部署を意味しているなら、集計前に表記をそろえた方がよいです。</p>
<div class="pdl-table-scroll"><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;"><code>unique()</code>で気づけること</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>営業部</code> と <code>営業</code> が混在</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">表記ゆれの可能性</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</code> で表記をそろえる</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>完了</code> と <code>完了済み</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>PC</code> と <code>パソコン</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></div>
<p>ここでは、修正方法を深掘りしすぎないようにします。<br/>
表記ゆれを実際に置換する方法は、<code>replace()</code> の記事で詳しく扱うと自然です。</p>
<p>関連記事：<br/>
<a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></p>
<h3><span id="toc13">表記ゆれを軽くそろえてから確認する例</span></h3>
<p>ここでは補足として、<code>営業</code> を <code>営業部</code> にそろえる例だけ見ておきます。</p>
<p>この記事の中心は <code>unique()</code> と <code>nunique()</code> なので、置換処理そのものは深掘りしません。</p>
<pre class="line-numbers"><code class="language-python">df_clean = df.copy()


df_clean["部署"] = df_clean["部署"].replace({
    "営業": "営業部"
})


df_clean["部署"].unique()</code></pre>
<div class="colab-cell-output">
<pre class="colab-output"><code>array(['営業部', '企画部', '人事部', &lt;NA&gt;], dtype=object)</code></pre>
</div>
<p>表記をそろえたあとに <code>unique()</code> を使うと、<code>営業</code> がなくなり、<code>営業部</code> にまとまったことを確認できます。</p>
<p>このように、<code>unique()</code> は「修正する前の確認」と「修正した後の確認」の両方で使えます。</p>
<h2><span id="toc14">groupby().nunique()でグループごとの種類数を確認する</span></h2>
<p>ここは応用ではなく、「こういう使い方もある」と軽く知っておく程度で大丈夫です。</p>
<p><code>nunique()</code> は、<code>groupby()</code> と組み合わせることもできます。</p>
<p>たとえば、部署ごとに何種類の商品カテゴリを扱っているかを確認したい場合です。</p>
<pre class="line-numbers"><code class="language-python">df_clean.groupby("部署")["商品カテゴリ"].nunique()</code></pre>
<div class="colab-cell-output">
<div class="pdl-table-scroll"><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;">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;">4</td></tr></tbody></table></div>
</div>
<p>このように、<code>groupby().nunique()</code> を使うと、グループごとの種類数を確認できます。</p>
<p>ただし、この記事では <code>groupby()</code> の詳しい使い方には深入りしません。<br/>
集計の考え方を詳しく学びたい場合は、<code>groupby×agg</code> の記事に進むとよいです。</p>
<p>関連記事：<br/>
<a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></p>
<h2><span id="toc15">duplicated()やdrop_duplicates()との違い</span></h2>
<p><code>unique()</code> と混同しやすいものに、<code>duplicated()</code> や <code>drop_duplicates()</code> があります。</p>
<div class="pdl-table-scroll"><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>unique()</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>nunique()</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>duplicated()</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>drop_duplicates()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">重複を除いたDataFrameやSeriesを作る</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">データの形を残して重複を取り除きたいときに使う</td>
</tr>
</tbody>
</table></div>
<p><code>duplicated()</code> は、重複している行を確認したいときに使います。<br/>
今回の記事の中心である <code>unique()</code>・<code>nunique()</code> は、列の値の種類を確認するためのものです。</p>
<p>関連記事：<br/>
<a href="https://pythondatalab.com/pandas-duplicated/">pandas duplicated()の使い方｜重複行の確認・subset・keepを初心者向けに解説</a></p>
<h2><span id="toc16">よくあるミスと注意点</span></h2>
<p>ここでは、初心者がつまずきやすいポイントを整理します。</p>
<h3><span id="toc17">unique()は元のDataFrameを書き換えない</span></h3>
<p><code>unique()</code> は、重複を除いた値の一覧を確認するメソッドです。<br/>
元のDataFrameから重複を削除する処理ではありません。</p>
<h3><span id="toc18">nunique()は値の一覧ではなく個数を返す</span></h3>
<p><code>nunique()</code> は、ユニークな値そのものではなく、種類数を返します。<br/>
値の中身を確認したい場合は、<code>unique()</code> を使います。</p>
<h3><span id="toc19">nunique()は標準では欠損値を数えない</span></h3>
<p>欠損値も含めて種類数を確認したい場合は、<code>nunique(dropna=False)</code> を使います。</p>
<h3><span id="toc20">value_counts()とは目的が違う</span></h3>
<p><code>value_counts()</code> は、値ごとの件数を見るためのメソッドです。<br/>
「一覧」「種類数」「件数」のどれを知りたいかで使い分けましょう。</p>
<h3><span id="toc21">unique()で表記ゆれを見つけても自動では直らない</span></h3>
<p><code>unique()</code> は表記ゆれを見つけるために便利ですが、値を自動で修正するわけではありません。<br/>
修正が必要な場合は、<code>replace()</code> などの前処理につなげます。</p>
<h2><span id="toc22">データ分析の流れの中でunique()・nunique()を使うタイミング</span></h2>
<p><code>unique()</code> と <code>nunique()</code> は、データ確認から前処理へ進むタイミングで役立ちます。</p>
<p>たとえば、次のような流れです。</p>
<div class="pdl-table-scroll"><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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>head()</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;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>info()</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>describe()</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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>unique()</code>・<code>nunique()</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;">5</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</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;">6</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>fillna()</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;">7</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>value_counts()</code>・<code>groupby()</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;">8</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></div>
<p>文章で書くと長く見えますが、流れとしては次のイメージです。</p>
<blockquote>
<p><strong>データを見る → 値の中身を確認する → 必要なら直す → 集計や可視化へ進む</strong></p>
</blockquote>
<p><code>info()</code> や <code>describe()</code> だけでは、文字列列にどんな値が入っているかまでは見えにくいことがあります。<br/>
そのため、カテゴリ列やステータス列では、<code>unique()</code> や <code>nunique()</code> を使って中身を確認することが大切です。</p>
<p>次に読みたい関連記事：<br/>
<a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></p>
<h2><span id="toc23">まとめ</span></h2>
<p>この記事では、Pandasの <code>unique()</code> と <code>nunique()</code> を使って、重複なしの値と種類数を確認する方法を解説しました。</p>
<p>ポイントを整理します。</p>
<ul>
<li><code>unique()</code> は、重複を除いた値の一覧を確認する</li>
<li><code>nunique()</code> は、重複を除いた値の種類数を確認する</li>
<li>値ごとの件数まで見たい場合は <code>value_counts()</code> を使う</li>
<li><code>count()</code> は欠損値以外の件数、<code>nunique()</code> は値の種類数を数える</li>
<li>欠損値も種類数に含めたい場合は <code>nunique(dropna=False)</code> を使う</li>
<li>表記ゆれを見つけるときは、まず <code>unique()</code> で列の値を確認する</li>
<li>グループごとの種類数は <code>groupby().nunique()</code> で確認できる</li>
<li><code>duplicated()</code> は重複行の確認が目的で、<code>unique()</code>・<code>nunique()</code> とは役割が違う</li>
</ul>
<p>データ分析では、いきなり集計や可視化に進む前に、列の中にどんな値が入っているかを確認することが大切です。</p>
<p><code>unique()</code> と <code>nunique()</code> を使えるようになると、表記ゆれ、カテゴリの種類、欠損値の扱いに気づきやすくなり、前処理の精度を上げやすくなります。</p>
<h2><span id="toc24">次に読みたい関連記事</span></h2>
<p>今回の記事とあわせて読むと、Pandasのデータ確認から前処理・集計までの流れがつかみやすくなります。</p>
<ul>
<li><p><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a><br/>
DataFrameの基本構造から確認したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a><br/>
データ全体の型・欠損値・統計量を確認したい方におすすめです。</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/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a><br/>
<code>unique()</code> で見つけた表記ゆれを直したい方におすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a><br/>
グループごとの集計を詳しく学びたい方におすすめです。</p>
</li>
</ul>
<p>必要に応じて、欠損値処理は <a href="https://pythondatalab.com/pandas-fillna/">fillna()の記事</a>、重複行の確認は <a href="https://pythondatalab.com/pandas-duplicated/">duplicated()の記事</a>、特定の値だけ抽出したい場合は <a href="https://pythondatalab.com/pandas-isin/">isin()の記事</a> も参考にしてください。</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> <div class="related-box"> <h3><span id="toc25"> カテゴリから探す</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>
</div>
<script>Prism.highlightAll();</script>



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

<p><code>unique()</code> は、列に含まれる値を重複なしで確認するメソッドです。<br />たとえば、<code>部署</code> 列に <code>営業部</code>、<code>企画部</code>、<code>人事部</code> など、どんな値が入っているかを確認できます。</p>

</div>
</div>
<div id="faq-question-1777978203404" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">unique()とnunique()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>unique()</code> は値の一覧を返します。<br /><code>nunique()</code> は値の種類数を返します。<br />値の中身を見たいときは <code>unique()</code>、何種類あるかだけ知りたいときは <code>nunique()</code> を使います。</p>

</div>
</div>
<div id="faq-question-1777978213804" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">unique()とvalue_counts()はどう使い分けますか？</span></h3>
<div class="rank-math-answer ">

<p>値の一覧だけ見たいときは <code>unique()</code> を使います。<br />値ごとの件数まで知りたいときは <code>value_counts()</code> を使います。<br />たとえば、部署名の種類を確認するだけなら <code>unique()</code>、部署ごとの件数まで確認するなら <code>value_counts()</code> が向いています。</p>

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

<p><code>count()</code> は、欠損値以外のデータ数を数えます。<br /><code>nunique()</code> は、重複を除いた値の種類数を数えます。<br />つまり、<code>count()</code> は「何件入っているか」、<code>nunique()</code> は「何種類あるか」を見るためのメソッドです。</p>

</div>
</div>
<div id="faq-question-1777978240951" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">nunique()は欠損値を数えますか？</span></h3>
<div class="rank-math-answer ">

<p>標準の <code>nunique()</code> は、欠損値を数えません。<br />欠損値も1種類として数えたい場合は、<code>nunique(dropna=False)</code> を使います。</p>

</div>
</div>
<div id="faq-question-1777978257766" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">unique()の結果にNaNや&lt;NA&gt;が出るのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>列の中に欠損値が含まれているためです。<br /><code>unique()</code> は、列に含まれる値の一覧を返すため、欠損値が結果に出ることがあります。<br />CSVから読み込んだデータでは <code>NaN</code>、Pandasの欠損値では <code>&lt;NA&gt;</code> のように表示されることがあります。</p>

</div>
</div>
<div id="faq-question-1777978270229" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">複数列に対してunique()は使えますか？</span></h3>
<div class="rank-math-answer ">

<p>基本的には、まず1列ずつ <code>df["列名"].unique()</code> の形で確認するのがおすすめです。<br />複数列を一度に確認する方法もありますが、初心者のうちは、列ごとに中身を確認した方が理解しやすいです。</p>

</div>
</div>
<div id="faq-question-1777978285069" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">グループごとにユニーク数を数えるにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p><code>groupby().nunique()</code> を使います。<br />たとえば、部署ごとに商品カテゴリの種類数を確認したい場合は、<br /><code>df.groupby("部署")["商品カテゴリ"].nunique()</code> のように書きます。</p>

</div>
</div>
<div id="faq-question-1777978300941" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">表記ゆれの確認にunique()は使えますか？</span></h3>
<div class="rank-math-answer ">

<p>はい、使えます。<br /><code>unique()</code> で列の値を一覧表示すると、<code>営業部</code> と <code>営業</code>、<code>完了</code> と <code>完了済み</code> のような表記ゆれに気づきやすくなります。<br />ただし、<code>unique()</code> は確認するためのメソッドなので、自動で修正するわけではありません。<br />表記を直す場合は、<code>replace()</code> などの前処理につなげます。</p>

</div>
</div>
<div id="faq-question-1777978321829" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">DataFrame全体で列ごとの種類数を確認できますか？</span></h3>
<div class="rank-math-answer ">

<p>はい、<code>df.nunique()</code> を使うと、各列のユニークな値の数をまとめて確認できます。<br />たとえば、<code>部署</code>、<code>商品カテゴリ</code>、<code>ステータス</code> など、複数の列について種類数を一度に見たいときに便利です。<br />ただし、初心者のうちは、まず <code>df["列名"].unique()</code> や <code>df["列名"].nunique()</code> のように、1列ずつ確認する方が理解しやすいです。<br />この記事では、まず基本として「1列の値を確認する」使い方を中心に扱っています。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-unique-nunique/">pandas unique()とnunique()の使い方｜値の一覧・種類数・value_counts()との違いを解説</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-unique-nunique/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</title>
		<link>https://pythondatalab.com/pandas-dt/</link>
					<comments>https://pythondatalab.com/pandas-dt/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Tue, 05 May 2026 06:58:00 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2036</guid>

					<description><![CDATA[<p>pandasの.dtを使って、日付列から年・月・日・曜日を取り出す方法を初心者向けに解説。to_datetime()との違い、月別集計・曜日別集計へのつなげ方、エラー対処も紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[

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

<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;
    overflow-x: auto;
  }
  .colab-article code {
    font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 1em 0;
    overflow-x: auto;
    display: block;
  }
  .colab-article table.wp-block-table th,
  .colab-article table.wp-block-table td {
    border: 1px solid #ddd;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>
<script>document.addEventListener("DOMContentLoaded", function(){ if (window.Prism) { Prism.highlightAll(); } });</script>

<div class="colab-article">


<p>CSVを読み込んだあと、<code>pd.to_datetime()</code>で日付列を日付型に変換できても、次のように迷うことがあります。</p>
<ul>
  <li>月別に売上を集計したい</li>
  <li>曜日ごとの傾向を見たい</li>
  <li>日付から年だけ、月だけを取り出したい</li>
  <li><code>df[&quot;注文日&quot;].dt.year</code> のような <code>.dt</code> が何をしているのかわからない</li>
</ul>
<p>結論からいうと、<strong><code>.dt</code>は、日付型の列から「年・月・日・曜日」などを取り出すために使う書き方</strong>です。</p>
<p>たとえば、日付列から月を取り出して「月」列を作ると、月別集計がしやすくなります。曜日を取り出すと、曜日別の売上や注文数を確認しやすくなります。</p>
<p>この記事では、pandasの<code>.dt</code>の使い方を、日付列から年・月・曜日を取り出し、集計や可視化につなげる流れでやさしく解説します。</p>

<h2><span id="toc1">まずはこの3行：日付から年・月・曜日を取り出す基本形</span></h2>
<p>急いで使い方だけ確認したい場合は、日付型に変換したあと、次のように書きます。</p>
<pre class="line-numbers"><code class="language-python">
df[&quot;注文日&quot;] = pd.to_datetime(df[&quot;注文日&quot;], errors=&quot;coerce&quot;)
df[&quot;月&quot;] = df[&quot;注文日&quot;].dt.month
df[&quot;曜日&quot;] = df[&quot;注文日&quot;].dt.day_name()
</code></pre>
<p>この3行の意味は、次の通りです。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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>pd.to_datetime()</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">文字列の日付を、Pandasで扱える日付型に変換する</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.month</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>.dt.day_name()</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付から曜日名を取り出す</td>
    </tr>
  </tbody>
</table>
<p>年を取り出したい場合は、<code>df[&quot;注文日&quot;].dt.year</code>を使います。 この記事では、この基本形をもとに、年・月・日・曜日の取り出し方と、月別集計・曜日別集計へのつなげ方を順番に見ていきます。</p>

<h2><span id="toc2">この記事でわかること</span></h2>
<p>このあと、次の内容を順番に見ていきます。</p>
<ul>
  <li>pandasの<code>.dt</code>とは何か</li>
  <li><code>.dt</code>を使う前に日付型へ変換する理由</li>
  <li><code>.dt.year</code>で年を取り出す方法</li>
  <li><code>.dt.month</code>で月を取り出す方法</li>
  <li><code>.dt.day</code>で日を取り出す方法</li>
  <li><code>.dt.day_name()</code>で曜日名を取り出す方法</li>
  <li><code>.dt.weekday</code>で曜日番号を取り出す方法</li>
  <li>英語の曜日名を日本語表示に整える基本</li>
  <li>取り出した年・月・曜日を新しい列として追加する方法</li>
  <li>月別集計・曜日別集計につなげる考え方</li>
  <li><code>.dt</code>でエラーになる原因と確認ポイント</li>
</ul>
<p>この記事では、<code>resample()</code>を使った本格的な時系列分析や、タイムゾーン、移動平均、時系列予測までは深入りしません。まずは、<strong>日付列を分析しやすい形に分解する基本</strong>に絞って解説します。</p>

<h2><span id="toc3">やりたいこと別：.dtの使い分け早見表</span></h2>
<p>日付データで迷ったときは、まず「何をしたいのか」から考えると選びやすくなります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;"><code>pd.to_datetime()</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVで読み込んだ日付列を整えるとき</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;"><code>.dt.year</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;">月を取り出したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.month</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;">日を取り出したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.day</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;">曜日名を取り出したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.day_name()</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;">曜日順に並べたい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.weekday</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;">年月で集計したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.strftime(&quot;%Y-%m&quot;)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">複数年データで月別推移を見たいとき</td>
    </tr>
  </tbody>
</table>
<p>この表の中でも、この記事では特に使用頻度が高い、<code>pd.to_datetime()</code> → <code>.dt.year</code> / <code>.dt.month</code> / <code>.dt.day_name()</code> の流れを中心に解説します。</p>

<h2><span id="toc4">.dtとは？日付列から年・月・曜日を取り出す書き方</span></h2>
<p><code>.dt</code>は、Pandasで日付列から年・月・日・曜日などを取り出すときに使う書き方です。</p>
<p>専門的には「日付・時刻用のアクセサ」と呼ばれますが、最初から用語を覚える必要はありません。まずは、<strong>日付列から必要な情報を取り出すための入口</strong>と考えるとわかりやすいです。</p>
<p>たとえば、次のように使います。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;"><code>df[&quot;注文日&quot;].dt.year</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026などの年</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;"><code>df[&quot;注文日&quot;].dt.month</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1〜12の月</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;"><code>df[&quot;注文日&quot;].dt.day</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1〜31の日</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;"><code>df[&quot;注文日&quot;].dt.day_name()</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Mondayなどの曜日名</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;"><code>df[&quot;注文日&quot;].dt.weekday</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">月曜0〜日曜6の番号</td>
    </tr>
  </tbody>
</table>
<p>ただし、ここで大切なのは、<strong><code>.dt</code>は日付型の列に対して使う</strong>という点です。 見た目が日付の文字列でも、型が<code>object</code>のままだと<code>.dt</code>を使えないことがあります。</p>

<h2><span id="toc5">to_datetime()と.dtの違い</span></h2>
<p><code>.dt</code>を理解する前に、<code>pd.to_datetime()</code>との違いを整理しておきましょう。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;">比較項目</th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>pd.to_datetime()</code></th>
      <th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt</code></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>
      <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;"><code>.dt</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;">例</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>pd.to_datetime(df[&quot;注文日&quot;])</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>df[&quot;注文日&quot;].dt.month</code></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;">変換できない値があると<code>NaT</code>になることがある</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">日付型でない列には使えない</td>
    </tr>
  </tbody>
</table>
<p>つまり、流れとしては次のように考えるとわかりやすいです。</p>
<ol>
  <li>まず、<code>pd.to_datetime()</code>で日付列を日付型に変換する</li>
  <li>そのあと、<code>.dt.year</code>や<code>.dt.month</code>で年・月・曜日を取り出す</li>
</ol>
<p>日付変換そのものを詳しく確認したい場合は、以下の記事を参考にしてください。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換とformat・NaT対処を初心者向けに解説</a></li>
</ul>

<h2><span id="toc6">この処理はどこで使う？日付変換の次に行う前処理</span></h2>
<p>ここまでで見たように、<code>.dt</code>は<code>pd.to_datetime()</code>で日付型に変換したあとのステップで使います。</p>
<p><strong>CSV読み込み → DataFrame確認 → 日付型への変換 → <code>.dt</code>で年・月・曜日を取り出す → 集計 → 可視化</strong></p>
<p>という流れで考えると、今回の<code>.dt</code>は、日付列を集計や可視化に使いやすくするための前処理にあたります。</p>
<p>CSVの読み込みは、以下の記事で詳しく解説しています。</p>
<ul>
  <li><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門｜pandasでread_csvとto_csvを解説</a></li>
</ul>
<p>DataFrameの基本や、型・欠損値の確認は以下の記事も参考になります。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
</ul>

<h2><span id="toc7">サンプルデータを用意する</span></h2>
<p>ここでは、ECサイトの注文データを想定します。コードが長くなりすぎないよう、6行だけの小さなデータで確認します。</p>
<p>列は、初心者が理解しやすいように次の3つだけにします。</p>
<ul>
  <li><code>注文日</code></li>
  <li><code>商品</code></li>
  <li><code>売上</code></li>
</ul>
<p><code>注文日</code>は、最初は文字列として入っている想定です。 CSVを読み込んだ直後も、日付列が文字列のままになっていることはよくあります。</p>

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

注文日 = [&quot;2026-01-05&quot;, &quot;2026-01-10&quot;, &quot;2026-02-03&quot;, &quot;2026-02-14&quot;, &quot;2026-03-08&quot;, &quot;2026-03-12&quot;]
商品 = [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;, &quot;モニター&quot;, &quot;マウス&quot;, &quot;キーボード&quot;]
売上 = [120000, 3000, 8000, 35000, 3200, 8500]

df = pd.DataFrame({&quot;注文日&quot;: 注文日,&quot;商品&quot;: 商品,&quot;売上&quot;: 売上})

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>
    </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;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3000</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">モニター</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">35000</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3200</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8500</td>
    </tr>
  </tbody>
</table>

<h2><span id="toc8">まずは日付列の型を確認する</span></h2>
<p><code>.dt</code>を使う前に、まず<code>注文日</code>列の型を確認します。</p>
<p>日付のように見えても、Pandas上では文字列として扱われていることがあります。 その場合、<code>.dt.year</code>や<code>.dt.month</code>をそのまま使うとエラーになる原因になります。</p>

<pre class="line-numbers"><code class="language-python">
df.dtypes
</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;">object</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;">object</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;">int64</td>
    </tr>
  </tbody>
</table>

<p>上のコードを実行すると、<code>注文日</code>が<code>object</code>型になっていることを確認できます。</p>
<p><code>object</code>型は、ざっくり言うと文字列として扱われている状態です。 このままでは、日付の部品を取り出す<code>.dt</code>を使う準備ができていません。</p>

<h2><span id="toc9">.dtを使う前にto_datetime()で日付型に変換する</span></h2>
<p><code>.dt</code>を使うために、<code>注文日</code>列を日付型に変換します。</p>
<p>実務では、日付列の中に変換できない値が混ざることがあります。 そのため、ここでは安全に<code>errors=&quot;coerce&quot;</code>を指定しています。</p>
<p><code>errors=&quot;coerce&quot;</code>を付けると、変換できない値があった場合に<code>NaT</code>になります。<code>NaT</code>は、日付データにおける欠損値のようなものです。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;注文日&quot;] = pd.to_datetime(df[&quot;注文日&quot;], errors=&quot;coerce&quot;)

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>
    </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;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3000</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">モニター</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">35000</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3200</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8500</td>
    </tr>
  </tbody>
</table>

<p>型も確認してみましょう。</p>

<pre class="line-numbers"><code class="language-python">
df.dtypes
</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;">datetime64[ns]</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;">object</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;">int64</td>
    </tr>
  </tbody>
</table>

<p><code>注文日</code>が<code>datetime64[ns]</code>になっていれば、<code>.dt</code>を使う準備ができています。</p>
<p>ここまでが、<code>.dt</code>を使う前の大切な準備です。 日付型への変換を深く学びたい場合は、<code>format=</code>や<code>NaT</code>対処も含めて、以下の記事で確認できます。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換とformat・NaT対処を初心者向けに解説</a></li>
</ul>

<h2><span id="toc10">.dt.yearで日付から年を取り出す</span></h2>
<p>年だけを取り出したいときは、<code>.dt.year</code>を使います。</p>
<p>たとえば、注文日から「何年の注文か」を新しい列にしたい場合に使えます。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;年&quot;] = df[&quot;注文日&quot;].dt.year

df[[&quot;注文日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
    </tr>
  </tbody>
</table>

<p><code>注文日</code>から、<code>2026</code>のような年だけを取り出せました。</p>
<p>ここで注意したいのは、<code>NaT</code>になっている行では、取り出した年も欠損になることです。 日付がない行から年を取り出すことはできないため、これは自然な結果です。</p>

<h2><span id="toc11">.dt.monthで日付から月を取り出す</span></h2>
<p>月だけを取り出したいときは、<code>.dt.month</code>を使います。</p>
<p>月別に売上を集計したい場合、まずは日付列から「月」列を作っておくとわかりやすくなります。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;月&quot;] = df[&quot;注文日&quot;].dt.month

df[[&quot;注文日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</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;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-10</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;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02-03</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;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02-14</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;">4</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-03-08</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;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
  </tbody>
</table>

<p><code>.dt.month</code>を使うと、1〜12の数値として月を取り出せます。</p>
<p>ただし、複数年のデータを扱う場合は注意が必要です。 <code>.dt.month</code>だけで集計すると、たとえば「2025年1月」と「2026年1月」が同じ「1月」としてまとめられてしまいます。</p>
<p>複数年データで年月単位にしたい場合は、後ほど紹介する<code>dt.strftime(&quot;%Y-%m&quot;)</code>のように、年と月を組み合わせた列を作ると安全です。</p>

<h2><span id="toc12">.dt.dayで日付から日を取り出す</span></h2>
<p>日付の「日」だけを取り出したいときは、<code>.dt.day</code>を使います。</p>
<p>たとえば、月の前半・後半で傾向を見たい場合や、日単位の確認をしたい場合に使えます。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;日&quot;] = df[&quot;注文日&quot;].dt.day

df[[&quot;注文日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">10</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;">2026-02-03</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;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">14</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
    </tr>
  </tbody>
</table>

<p><code>.dt.day</code>では、1〜31の「日」を取り出せます。</p>
<p>ここでの「日」は日付の中の1日、2日、3日のような値です。 曜日を取り出す処理とは別なので、混同しないようにしましょう。</p>

<h2><span id="toc13">.dt.day_name()で曜日名を取り出す</span></h2>
<p>曜日名を取り出したいときは、<code>.dt.day_name()</code>を使います。</p>
<p>曜日別に売上や注文数を見たいときに役立ちます。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;曜日&quot;] = df[&quot;注文日&quot;].dt.day_name()

df[[&quot;注文日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Tuesday</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Sunday</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Thursday</td>
    </tr>
  </tbody>
</table>

<p><code>.dt.day_name()</code>を使うと、<code>Monday</code>や<code>Tuesday</code>のように英語の曜日名が取り出されます。</p>
<p>英語の曜日名のままでも集計はできます。 ただし、ブログ記事やレポートで見せる場合は、日本語の曜日にしたいこともあります。</p>
<p>その場合は、<code>.dt.day_name()</code>で取り出した曜日名を、<code>map()</code>で日本語に置き換えるとわかりやすくなります。</p>

<pre class="line-numbers"><code class="language-python">
weekday_map = {
    &quot;Monday&quot;: &quot;月曜日&quot;,
    &quot;Tuesday&quot;: &quot;火曜日&quot;,
    &quot;Wednesday&quot;: &quot;水曜日&quot;,
    &quot;Thursday&quot;: &quot;木曜日&quot;,
    &quot;Friday&quot;: &quot;金曜日&quot;,
    &quot;Saturday&quot;: &quot;土曜日&quot;,
    &quot;Sunday&quot;: &quot;日曜日&quot;
}

df[&quot;曜日_日本語&quot;] = df[&quot;曜日&quot;].map(weekday_map)

df[[&quot;注文日&quot;, &quot;曜日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Tuesday</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Sunday</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Thursday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">木曜日</td>
    </tr>
  </tbody>
</table>

<p>ここでは、<code>.dt.day_name()</code>で取り出した英語の曜日名を、日本語の曜日名に置き換えました。</p>
<p>ただし、この記事では<code>.dt</code>の基本を優先するため、以降の集計例では、先に作った<code>曜日</code>列と<code>曜日番号</code>列を使って説明します。 曜日名の置き換え自体を詳しく学びたい場合は、<code>map()</code>や<code>replace()</code>の記事とつなげて考えると理解しやすくなります。</p>

<h2><span id="toc14">.dt.weekdayで曜日番号を取り出す</span></h2>
<p>曜日を番号で扱いたい場合は、<code>.dt.weekday</code>を使います。</p>
<p><code>.dt.weekday</code>では、曜日が次の番号で表されます。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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</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>
    <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;">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;">4</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;">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;">6</td>
    </tr>
  </tbody>
</table>
<p>曜日順に並べたいときは、曜日名だけでなく曜日番号も持っておくと便利です。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;曜日番号&quot;] = df[&quot;注文日&quot;].dt.weekday

df[[&quot;注文日&quot;, &quot;曜日&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</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;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Tuesday</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;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Sunday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">6</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Thursday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
    </tr>
  </tbody>
</table>

<p>曜日名だけで集計すると、表示順がアルファベット順になることがあります。 曜日番号を一緒に持っておくと、月曜から日曜の順に並べやすくなります。</p>

<h2><span id="toc15">処理前と処理後を比較する</span></h2>
<p>ここまでで、<code>注文日</code>から年・月・日・曜日を取り出して、新しい列として追加しました。</p>
<p>処理前と処理後のイメージを比較すると、<code>.dt</code>の役割がわかりやすくなります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;">注文日、商品、売上</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>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">月別・曜日別の集計に使いやすい</td>
    </tr>
  </tbody>
</table>
<p><code>.dt</code>は、元の日付列を消すためのものではありません。 <strong>日付列から分析しやすい列を作るためのもの</strong>と考えると理解しやすいです。</p>

<pre class="line-numbers"><code class="language-python">
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>
      <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;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">ノートPC</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</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>
    <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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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>
      <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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Tuesday</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>
      <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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">モニター</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">35000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</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>
      <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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">マウス</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3200</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Sunday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">日曜日</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">6</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">キーボード</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8500</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Thursday</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>
  </tbody>
</table>

<h2><span id="toc16">よく使う.dtの取り出し項目</span></h2>
<p><code>.dt</code>には多くの機能がありますが、初心者が最初に覚えるなら、まずは次の項目で十分です。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;"><code>.dt.year</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;">月</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.month</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;">日</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.day</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;">曜日名</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.day_name()</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;">曜日番号</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.weekday</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;">四半期</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.quarter</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1〜4四半期で見る</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;"><code>.dt.date</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">時刻を除いた日付を確認する</td>
    </tr>
  </tbody>
</table>
<p><code>.dt.quarter</code>や<code>.dt.date</code>も便利ですが、この記事では深掘りしません。 まずは、年・月・日・曜日を取り出せるようになることを優先しましょう。</p>

<h2><span id="toc17">年月単位で集計したいときはdt.strftime(&quot;%Y-%m&quot;)も使う</span></h2>
<p><code>.dt.month</code>は、1〜12の月だけを取り出します。</p>
<p>そのため、複数年のデータで月別集計をするときは、<code>2026-01</code>のような年月列を作ると便利です。 このように表示形式を整えたいときは、<code>.dt.strftime(&quot;%Y-%m&quot;)</code>を使えます。</p>

<pre class="line-numbers"><code class="language-python">
df[&quot;年月&quot;] = df[&quot;注文日&quot;].dt.strftime(&quot;%Y-%m&quot;)

df[[&quot;注文日&quot;, &quot;年&quot;, &quot;月&quot;, &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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01</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;">2026-01-10</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01</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;">2026-02-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02</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;">2026-02-14</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-02</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;">2026-03-08</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-03</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;">2026-03-12</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-03</td>
    </tr>
  </tbody>
</table>

<p><code>dt.strftime(&quot;%Y-%m&quot;)</code>を使うと、<code>2026-01</code>のような年月の文字列を作れます。</p>
<p>ここでは軽く紹介するだけにします。 表示形式を自由に整える処理は便利ですが、最初から細かく覚えすぎるより、まずは<code>.dt.year</code>、<code>.dt.month</code>、<code>.dt.day_name()</code>の基本を押さえるのがおすすめです。</p>

<h2><span id="toc18">月別売上を集計する</span></h2>
<p><code>.dt</code>で月や年月の列を作ると、<code>groupby()</code>で月別集計がしやすくなります。</p>
<p>ここでは、<code>年月</code>ごとに売上合計を集計してみます。</p>
<p>なお、今回のサンプルには、日付に変換できなかった<code>NaT</code>の行があります。 月別集計では、まずは初心者が読みやすいように、<code>注文日</code>が欠損していない行だけを対象にします。</p>

<pre class="line-numbers"><code class="language-python">
monthly_sales = (
    df.dropna(subset=[&quot;注文日&quot;])
      .groupby(&quot;年月&quot;, as_index=False)[&quot;売上&quot;]
      .sum()
)

monthly_sales
</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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">123000</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;">2026-02</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">43000</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;">2026-03</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">11700</td>
    </tr>
  </tbody>
</table>

<p><code>年月</code>ごとに売上を合計できました。</p>
<p>このように、<code>.dt</code>で取り出した値は、集計のキーとして使えます。 <code>groupby()</code>の基本を詳しく学びたい場合は、以下の記事も参考になります。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
</ul>

<h2><span id="toc19">曜日別売上を集計する</span></h2>
<p>次に、曜日別に売上を集計してみます。</p>
<p>曜日名だけだと並び順がわかりにくくなるため、ここでは<code>曜日番号</code>も使って並べます。</p>

<pre class="line-numbers"><code class="language-python">
weekday_sales = (
    df.dropna(subset=[&quot;注文日&quot;])
      .groupby([&quot;曜日番号&quot;, &quot;曜日&quot;], as_index=False)[&quot;売上&quot;]
      .sum()
      .sort_values(&quot;曜日番号&quot;)
)

weekday_sales
</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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">120000</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;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Tuesday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">3</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Thursday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8500</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;">5</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Saturday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">38000</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;">6</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Sunday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">3200</td>
    </tr>
  </tbody>
</table>

<p>曜日ごとの売上合計を確認できました。</p>
<p>曜日名だけでなく曜日番号も作っておくと、月曜から日曜の順に並べやすくなります。 曜日別の件数だけを確認したい場合は、<code>value_counts()</code>を使う方法もあります。</p>

<pre class="line-numbers"><code class="language-python">
df.dropna(subset=[&quot;注文日&quot;])[&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;">Saturday</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;">Monday</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;">Tuesday</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;">Sunday</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;">Thursday</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
    </tr>
  </tbody>
</table>

<p><code>value_counts()</code>は、曜日ごとの件数を数えたいときに便利です。</p>
<p>ここでも、日付がない行は曜日を判断できないため、<code>dropna(subset=[&quot;注文日&quot;])</code>で除外してから数えています。</p>
<ul>
  <li>合計や平均を出したい → <code>groupby()</code></li>
  <li>件数を数えたい → <code>value_counts()</code></li>
</ul>
<p>このように使い分けると、日付データを分析に使いやすくなります。</p>
<p><code>value_counts()</code>について詳しく知りたい場合は、以下の記事も参考になります。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
</ul>

<h2><span id="toc20">月別・曜日別に何を見たいかで使い分ける</span></h2>
<p><code>.dt</code>で日付を分解するときは、「何を見たいのか」から逆算すると迷いにくくなります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;"><code>.dt.year</code>で年列を作る</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>groupby(&quot;年&quot;)</code></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;"><code>.dt.month</code>または年月列を作る</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>groupby(&quot;月&quot;)</code>または<code>groupby(&quot;年月&quot;)</code></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;"><code>.dt.day_name()</code>や<code>.dt.weekday</code>を使う</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">曜日別の<code>groupby()</code></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>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>value_counts()</code></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>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Matplotlibの棒グラフ・折れ線グラフ</td>
    </tr>
  </tbody>
</table>
<p><code>.dt</code>は最終目的ではなく、<strong>集計や可視化をしやすくするための前処理</strong>です。</p>

<h2><span id="toc21">.dtでよくあるエラーと原因</span></h2>
<p><code>.dt</code>で初心者がつまずきやすいのは、日付型に変換する前に使ってしまうケースです。</p>
<p>たとえば、次のように文字列のまま<code>.dt.year</code>を使うと、エラーになります。</p>

<pre class="line-numbers"><code class="language-python">
df_error = pd.DataFrame({
    &quot;注文日&quot;: [&quot;2026-01-01&quot;, &quot;2026-01-02&quot;]
})

try:
    df_error[&quot;注文日&quot;].dt.year
except Exception as e:
    print(type(e).__name__)
    print(e)
</code></pre>

<pre>AttributeError
Can only use .dt accessor with datetimelike values</pre>

<p>このエラーは、<code>注文日</code>列がまだ日付型ではないことが原因です。</p>
<p>対処法は、次の流れです。</p>
<ol>
  <li><code>df.dtypes</code>や<code>df.info()</code>で型を確認する</li>
  <li><code>pd.to_datetime()</code>で日付型へ変換する</li>
  <li>そのあとに<code>.dt.year</code>や<code>.dt.month</code>を使う</li>
</ol>
<p>型の確認方法は、以下の記事でも詳しく解説しています。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
</ul>

<h2><span id="toc22">NaTがある列に.dtを使うとどうなるか</span></h2>
<p>日付に変換できない値があると、<code>pd.to_datetime()</code>で<code>NaT</code>になることがあります。</p>
<p>ここでは、本文のメインデータとは別に、<code>未入力</code>を含む小さなデータで確認します。</p>

<pre class="line-numbers"><code class="language-python">
df_nat = pd.DataFrame({
    &quot;注文日&quot;: [&quot;2026-01-05&quot;, &quot;未入力&quot;]
})

df_nat[&quot;注文日&quot;] = pd.to_datetime(df_nat[&quot;注文日&quot;], errors=&quot;coerce&quot;)
df_nat[&quot;年&quot;] = df_nat[&quot;注文日&quot;].dt.year
df_nat[&quot;月&quot;] = df_nat[&quot;注文日&quot;].dt.month
df_nat[&quot;曜日&quot;] = df_nat[&quot;注文日&quot;].dt.day_name()

df_nat
</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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026-01-05</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2026</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">Monday</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;">NaT</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaT</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaT</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">NaT</td>
    </tr>
  </tbody>
</table>

<p><code>未入力</code>は日付に変換できないため、<code>NaT</code>になりました。</p>
<p><code>NaT</code>の行では、年・月・曜日も欠損になります。 日付がない行から、年や曜日を取り出すことはできないためです。</p>
<p><code>NaT</code>が多い場合は、まず日付列の欠損や変換できない値を確認することが大切です。 欠損値の確認や処理は、以下の記事ともつながります。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-isnull/">欠損値を可視化して攻略！Pandas isnullとヒートマップ活用術</a></li>
  <li><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></li>
</ul>

<h2><span id="toc23">.dtで作った列は新しい列として残すと分析しやすい</span></h2>
<p><code>.dt.year</code>や<code>.dt.month</code>で取り出した値は、その場で見るだけでなく、新しい列として残しておくと便利です。</p>
<p>たとえば、次のような列があると、後から集計や抽出をしやすくなります。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;">年別の比較</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>
    <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>新しい列の追加そのものを詳しく知りたい場合は、以下の記事も参考になります。</p>
<ul>
  <li>[pandasで新しい列を追加する方法｜df[&#x27;列名&#x27;]・assign・条件付き列追加を初心者向けに解説](https://pythondatalab.com/pandas-add-column/)</li>
</ul>

<h2><span id="toc24">可視化につなげるときの考え方</span></h2>
<p><code>.dt</code>で月や曜日を取り出したら、そのままグラフ化するのではなく、まず集計表を作ると流れが整理しやすくなります。</p>
<p>たとえば、次のような流れです。</p>
<ol>
  <li><code>注文日</code>を日付型に変換する</li>
  <li><code>.dt</code>で<code>年月</code>や<code>曜日</code>列を作る</li>
  <li><code>groupby()</code>で月別・曜日別に集計する</li>
  <li>Matplotlibで棒グラフや折れ線グラフにする</li>
</ol>
<p>この記事では可視化の細かい設定までは扱いません。 グラフ化を学びたい場合は、以下の記事へ進むと理解がつながります。</p>
<ul>
  <li><a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a></li>
  <li><a href="https://pythondatalab.com/matplotlib-line-legend-color/">Matplotlib折れ線グラフの描き方</a></li>
</ul>

<h2><span id="toc25">軽く知っておくと便利な.dtの関連機能</span></h2>
<p>最後に、発展的ですが、名前だけ知っておくと便利な機能を軽く紹介します。</p>
<table class="wp-block-table" style="width: auto; border-collapse: collapse;">
  <thead>
    <tr>
      <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;"><code>.dt.strftime()</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>.dt.quarter</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">四半期を取り出す</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">名前だけ知っておけばOK</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>.dt.date</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>resample()</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>
<p>最初から全部を覚える必要はありません。 まずは、<code>.dt.year</code>、<code>.dt.month</code>、<code>.dt.day_name()</code>を使って、日付列を分析しやすい列に分けられるようになることを優先しましょう。</p>

<h2><span id="toc26">まとめ：.dtは日付を分析に使いやすくする前処理</span></h2>
<p>この記事では、pandasの<code>.dt</code>アクセサを使って、日付から年・月・日・曜日を取り出す方法を解説しました。</p>
<p>ポイントを整理します。</p>
<ul>
  <li><code>.dt</code>は、日付型の列から年・月・曜日などを取り出すために使う</li>
  <li><code>.dt</code>を使う前に、<code>pd.to_datetime()</code>で日付型へ変換する</li>
  <li><code>.dt.year</code>で年を取り出せる</li>
  <li><code>.dt.month</code>で月を取り出せる</li>
  <li><code>.dt.day</code>で日を取り出せる</li>
  <li><code>.dt.day_name()</code>で曜日名を取り出せる</li>
  <li><code>.dt.weekday</code>で曜日番号を取り出せる</li>
  <li>複数年データの月別集計では、<code>dt.strftime(&quot;%Y-%m&quot;)</code>で年月列を作ると便利</li>
  <li>取り出した値は、新しい列として追加すると集計や可視化に使いやすい</li>
  <li><code>.dt</code>でエラーになるときは、まず日付列の型を確認する</li>
</ul>
<p><code>.dt</code>は、日付データ分析のゴールではありません。 <strong>日付列を、集計や可視化に使える形へ整えるための前処理</strong>です。</p>
<p>日付型への変換は<code>to_datetime()</code>、集計は<code>groupby()</code>や<code>value_counts()</code>、グラフ化はMatplotlibへ進むと、データ分析の流れが自然につながります。</p>

<h2><span id="toc27">次に読みたい関連記事</span></h2>
<p>今回の記事とあわせて読むと、Pandasの日付データ分析の流れが理解しやすくなります。</p>
<h3><span id="toc28">基礎・CSV読み込み</span></h3>
<ul>
  <li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a></li>
  <li><a href="https://pythondatalab.com/google-colab-csv/">Google Colab CSV 読み込み＆保存入門｜pandasでread_csvとto_csvを解説</a></li>
</ul>
<h3><span id="toc29">型確認・日付変換</span></h3>
<ul>
  <li><a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い｜欠損値・型・統計量の見方を例で解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-to-datetime/">pandas to_datetime()の使い方｜文字列の日付変換とformat・NaT対処を初心者向けに解説</a></li>
</ul>
<h3><span id="toc30">列追加・集計</span></h3>
<ul>
  <li><a href="https://pythondatalab.com/pandas-add-column/">pandasで新しい列を追加する方法｜df[‘列名’]・assign・条件付き列追加を初心者向けに解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-map/">pandas map()の使い方｜辞書で値を変換・新しい列を作る方法を初心者向けに解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-sort/">pandas 並び替え（sort）入門｜sort_values・sort_indexの違いと複数列ソート</a></li>
</ul>
<h3><span id="toc31">可視化</span></h3>
<ul>
  <li><a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a></li>
  <li><a href="https://pythondatalab.com/matplotlib-line-legend-color/">Matplotlib折れ線グラフの描き方</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="toc32"> カテゴリから探す</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>

</div>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1777967205224" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">pandasの.dtとは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>.dt</code>は、日付型の列から年・月・日・曜日などを取り出すための書き方です。 <br />たとえば、<code>df["注文日"].dt.year</code>で年、<code>df["注文日"].dt.month</code>で月を取り出せます。</p>

</div>
</div>
<div id="faq-question-1777967231842" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">.dtを使うとエラーになるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>多くの場合、対象の列が日付型ではなく<code>object</code>型の文字列になっていることが原因です。 まず<code>df.dtypes</code>や<code>df.info()</code>で型を確認し、必要に応じて<code>pd.to_datetime()</code>で日付型に変換してから<code>.dt</code>を使います。</p>

</div>
</div>
<div id="faq-question-1777967250513" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">to_datetime()と.dtは何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>to_datetime()</code>は、文字列などを日付型に変換するために使います。 <code>.dt</code>は、日付型に変換したあと、その日付から年・月・曜日などを取り出すために使います。</p>

</div>
</div>
<div id="faq-question-1777967264426" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc36">日付から年や月だけを取り出すにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>年だけを取り出す場合は、<code>df["注文日"].dt.year</code>を使います。 月だけを取り出す場合は、<code>df["注文日"].dt.month</code>を使います。<br />取り出した年や月を分析に使いたい場合は、<br /><code>df["年"] = df["注文日"].dt.year</code>、<code>df["月"] = df["注文日"].dt.month</code>のように新しい列として追加すると便利です。</p>

</div>
</div>
<div id="faq-question-1777967285969" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc37">日付から曜日を取得するにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>曜日名を取り出したい場合は、<code>df["注文日"].dt.day_name()</code>を使います。 曜日順に並べたい場合は、<code>df["注文日"].dt.weekday</code>で曜日番号も作っておくと便利です。<br /><code>.dt.day_name()</code>で取り出した曜日名は英語になるため、日本語で見せたい場合は、<code>map()</code>で「Monday → 月曜日」のように置き換える方法があります。</p>

</div>
</div>
<div id="faq-question-1777967309106" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc38">.dt.weekdayと.dt.day_name()は何が違いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>.dt.day_name()</code>は、<code>Monday</code>や<code>Tuesday</code>のような曜日名を返します。 <code>.dt.weekday</code>は、月曜日を0、日曜日を6とする曜日番号を返します。 見やすく表示したいなら曜日名、曜日順に並べたいなら曜日番号が便利です。</p>

</div>
</div>
<div id="faq-question-1777967318479" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc39">月別集計をするには、.dt.monthだけでよいですか？</span></h3>
<div class="rank-math-answer ">

<p>同じ年のデータだけなら、<code>.dt.month</code>で月列を作って集計してもわかりやすいです。 ただし、複数年のデータでは、<code>2025年1月</code>と<code>2026年1月</code>が同じ<code>1月</code>として混ざる可能性があります。 その場合は、<code>dt.strftime("%Y-%m")</code>で年月列を作ると安全です。</p>

</div>
</div>
<div id="faq-question-1777967334697" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc40">NaTがある列に.dtを使っても大丈夫ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>NaT</code>がある列にも<code>.dt</code>を使える場合があります。 ただし、<code>NaT</code>の行では、年・月・曜日などの結果も欠損になります。 集計に使うときは、必要に応じて<code>dropna(subset=["注文日"])</code>で日付がない行を除外してから集計すると、結果を読みやすくできます。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-dt/">pandas dtの使い方｜日付から年・月・曜日を取り出す方法を初心者向けに解説</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-dt/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>

<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 apply()の使い方｜axis=1で行ごとに処理・lambda・mapとの違いを解説</title>
		<link>https://pythondatalab.com/pandas-apply/</link>
					<comments>https://pythondatalab.com/pandas-apply/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Mon, 04 May 2026 09:43:38 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2025</guid>

					<description><![CDATA[<p>pandasのapply()で列や行に関数を適用する方法を初心者向けに解説。axis=1で行ごとに処理する考え方、lambdaや自作関数、map・replace・astype・np.whereとの違いも整理します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-apply/">pandas apply()の使い方｜axis=1で行ごとに処理・lambda・mapとの違いを解説</a> first appeared on <a rel="nofollow" href="https://pythondatalab.com">Python Data Lab（Pythonデータラボ）</a>.&lt;/p&gt;</p>
]]></description>
										<content:encoded><![CDATA[

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

<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 {
    line-height: 1.8;
  }
  .colab-article pre[class*="language-"],
  .colab-article pre.line-numbers {
    margin: 0 !important;
    padding: 1em !important;
    overflow-x: auto;
  }
  .colab-article code {
    font-family: Consolas, Menlo, Monaco, "Courier New", monospace;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    margin: 1em 0;
    overflow-x: auto;
    display: block;
    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;
    overflow-x: auto;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>

<div class="colab-article">


<p>CSVを読み込んで前処理をしていると、次のような場面がよく出てきます。</p>
<ul>
  <li>点数から「合格」「再確認」の列を作りたい</li>
  <li>購入金額から「通常顧客」「見込み顧客」「重点顧客」のような区分を作りたい</li>
  <li>複数の列を見て、1行ずつ判定したい</li>
  <li>自分で作った関数を、DataFrameの列や行にまとめて使いたい</li>
</ul>
<p>このようなときに使えるのが、Pandasの <code>apply()</code> です。</p>
<p>ただし、<code>apply()</code> は便利な一方で、何でも <code>apply()</code> で書けばよいわけではありません。 1列の値を対応表で変換するだけなら <code>map()</code>、値の置換なら <code>replace()</code>、型を変えるだけなら <code>astype()</code> や <code>to_datetime()</code> の方がわかりやすいこともあります。</p>
<p>この記事では、<code>apply()</code> を「何となく使う」のではなく、<strong>どの場面で使うべきか</strong>、<strong><code>axis=1</code> は何を意味するのか</strong>、<strong><code>lambda</code> と自作関数をどう使い分けるか</strong>を、初心者向けに順番に解説します。</p>
<p>この記事を読むと、<code>apply()</code> の書き方を覚えるだけでなく、「<code>map()</code> で十分な場面」「<code>apply(axis=1)</code> を使うべき場面」「<code>lambda</code> ではなく自作関数に分けた方がよい場面」を判断できるようになります。</p>
<p>そのため、CSV読み込み後の前処理で、列を整えたり、複数列から判定列を作ったり、集計しやすいデータに変換したりする流れが理解しやすくなります。</p>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、次の内容を扱います。</p>
<ul>
  <li><code>apply()</code> がどんな場面で役立つか</li>
  <li><code>Series.apply()</code> と <code>DataFrame.apply()</code> の違い</li>
  <li><code>lambda</code> を使った基本的な書き方</li>
  <li><code>axis=0</code> と <code>axis=1</code> の違い</li>
  <li>複数列を使って新しい列を作る方法</li>
  <li><code>apply()</code>、<code>map()</code>、<code>replace()</code>、<code>astype()</code>、<code>np.where()</code> の使い分け</li>
  <li><code>apply()</code> でよくあるミスと注意点</li>
  <li><code>apply()</code> で作った列を、集計や可視化の前処理につなげる考え方</li>
</ul>
<p>この記事のゴールは、<code>apply()</code> を、<code>map()</code> や <code>replace()</code> では足りないときに使う「関数適用の道具」として理解し、1列処理・行ごとの処理・新しい列作成を安全に使い分けられるようになることです。</p>

<h2><span id="toc2">データ分析の流れの中でのapply()の位置づけ</span></h2>
<p><code>apply()</code> は、DataFrameを読み込んだ直後に最初に使う機能というより、データを確認したあとに、分析しやすい形へ整える前処理でよく使います。</p>
<p>たとえば、次のような流れです。</p>
<ol>
  <li><code>head()</code>、<code>info()</code>、<code>describe()</code> でデータの中身を確認する</li>
  <li><code>rename()</code>、<code>replace()</code>、<code>astype()</code>、<code>to_datetime()</code> などで列名・値・型を整える</li>
  <li><code>map()</code> や <code>apply()</code> で、分析しやすい列を作る</li>
  <li><code>value_counts()</code> や <code>groupby()</code> で集計する</li>
  <li>Matplotlibで可視化する</li>
</ol>
<p>つまり <code>apply()</code> は、<strong>前処理から集計・可視化へ進むために、必要な列を作る道具</strong>として考えるとわかりやすいです。</p>

<h2><span id="toc3">先に結論：apply()は「関数を列や行に適用する」ときに使う</span></h2>
<p><code>apply()</code> は、Pandasの列や行に対して、同じ処理をまとめて適用するためのメソッドです。</p>
<p>たとえば、次のような処理に向いています。</p>
<ul>
  <li>1列の値をもとに、判定結果を作る</li>
  <li>複数列を見て、1行ごとに区分を作る</li>
  <li>自作関数をDataFrameに適用する</li>
  <li>短い処理を <code>lambda</code> で書く</li>
</ul>
<p>特に、次のように判断すると迷いにくくなります。</p>
<blockquote><p>1列の対応表変換なら <code>map()</code>、値の置換なら <code>replace()</code>、型変換なら <code>astype()</code>、複数列を見て1行ずつ判定するなら <code>apply(axis=1)</code> を検討します。</p></blockquote>
<p><code>apply()</code> は、単純な置換や型変換よりも、<strong>自分で作った判定ルールや関数を列・行に適用したいとき</strong>に向いています。</p>
<p>一方で、<code>apply()</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;">1列を辞書で変換したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>map()</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;">値を別の値に置き換えたい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</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;">文字列を数値型に変えたい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>astype()</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;">日付文字列を日付型にしたい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>to_datetime()</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;">単純な条件で2択に分けたい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>np.where()</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;">関数を列に適用したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>apply()</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;">複数列を見て1行ずつ判定したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>apply(axis=1)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">行ごとの処理を書きやすい</td>
    </tr>
  </tbody>
</table>
<p>なお、この記事では「新しい列を作る方法全体」ではなく、<strong>apply()を使って関数の結果を列として追加する場面</strong>に絞って解説します。 <code>df[&quot;新しい列&quot;] = ...</code> や <code>assign()</code> など、列追加そのものの基本は、別記事の「pandasで新しい列を追加する方法」で整理すると理解しやすいです。</p>
<p>初心者のうちは、<strong>単純な処理まで何でも <code>apply()</code> にしない</strong>ことが大切です。</p>
<p>💡 <strong>ポイント</strong> <code>apply()</code> は便利ですが、何でも <code>apply()</code> で書く必要はありません。まずは <code>map()</code>・<code>replace()</code>・<code>astype()</code> で書けないかを確認し、それでも関数を適用したいときに <code>apply()</code> を使うと整理しやすくなります。</p>
<p><code>apply()</code> は、「ほかの方法では書きにくい処理を、関数として適用したいとき」に使うと考えると整理しやすくなります。</p>

<h2><span id="toc4">サンプルデータを用意する</span></h2>
<p>この記事では、Google Colabでそのまま試せるように、小さなサンプルDataFrameを使います。</p>
<p>学習データと購買データが混ざったような例にして、<code>apply()</code> で「合否」「税込金額」「顧客区分」などを作っていきます。</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;: [22, 35, 41, 29, 52, 38],
    &quot;点数&quot;: [82, 59, 74, 91, 66, 88],
    &quot;出席率&quot;: [0.95, 0.70, 0.82, 0.98, 0.60, 0.90],
    &quot;購入金額&quot;: [12000, 45000, 28000, 62000, 8000, 37000],
    &quot;地域&quot;: [&quot;東京&quot;, &quot;大阪&quot;, &quot;東京&quot;, &quot;福岡&quot;, &quot;札幌&quot;, &quot;大阪&quot;]
})

df</code></pre>

<div class="colab-output">
<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>
      <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;">22</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">82</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.95</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">35</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">59</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.7</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">45000</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;">41</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">74</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.82</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">28000</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;">29</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">91</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.98</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">62000</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;">52</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">66</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.6</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">38</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">88</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.9</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">37000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">大阪</td>
    </tr>
  </tbody>
</table>
</div>

<h2><span id="toc5">1. Series.apply()で1列に処理を適用する</span></h2>
<p>まずは、1列だけに <code>apply()</code> を使う基本形です。</p>
<p>1列に対して使う場合は、<code>df[&quot;列名&quot;].apply(関数)</code> のように書きます。 これは <code>Series.apply()</code> と呼ばれる使い方です。</p>
<p>次の例では、<code>点数</code> 列をもとに、80点以上なら「合格」、それ以外なら「再確認」とする列を作ります。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;判定&quot;] = df[&quot;点数&quot;].apply(lambda x: &quot;合格&quot; if x &gt;= 80 else &quot;再確認&quot;)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;判定&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">82</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;">59</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;">74</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;">91</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;">66</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;">88</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">合格</td>
    </tr>
  </tbody>
</table>
</div>

<p><code>lambda x:</code> は、「列の値を1つずつ受け取って処理する短い関数」と考えるとわかりやすいです。</p>
<p>上の例では、<code>点数</code> 列の値が1つずつ <code>x</code> に入り、条件に応じて「合格」または「再確認」が返されます。</p>
<p>ただし、条件が長くなる場合は、<code>lambda</code> に無理やり詰め込まない方が読みやすくなります。 その場合は、次のように自作関数に分けるのがおすすめです。</p>

<h2><span id="toc6">2. 自作関数をapply()に渡す</span></h2>
<p><code>apply()</code> には、<code>lambda</code> だけでなく、自分で定義した関数も渡せます。</p>
<p>条件が2つ以上ある場合や、あとで読み返したい処理は、自作関数に分けると見通しがよくなります。</p>

<pre class="line-numbers"><code class="language-python">def score_label(score):
    if score &gt;= 80:
        return &quot;高得点&quot;
    elif score &gt;= 70:
        return &quot;標準&quot;
    else:
        return &quot;要復習&quot;

df[&quot;点数区分&quot;] = df[&quot;点数&quot;].apply(score_label)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;点数区分&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">82</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;">59</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;">74</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;">91</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;">66</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;">88</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">高得点</td>
    </tr>
  </tbody>
</table>
</div>

<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;"><code>lambda</code></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;">条件が複数ある処理</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>lambda</code> は便利ですが、初心者向けの記事では、複雑な条件ほど自作関数の方が理解しやすいことが多いです。</p>

<h2><span id="toc7">3. map()との違い：対応表があるならmap()が読みやすい</span></h2>
<p><code>apply()</code> とよく比較されるのが <code>map()</code> です。</p>
<p><code>map()</code> は、1列の値を辞書などの対応表で変換するときに向いています。 たとえば、地域名からエリア名を作るような処理です。</p>

<pre class="line-numbers"><code class="language-python">area_map = {
    &quot;東京&quot;: &quot;関東&quot;,
    &quot;大阪&quot;: &quot;関西&quot;,
    &quot;福岡&quot;: &quot;九州&quot;,
    &quot;札幌&quot;: &quot;北海道&quot;
}

df[&quot;エリア&quot;] = df[&quot;地域&quot;].map(area_map)

df[[&quot;名前&quot;, &quot;地域&quot;, &quot;エリア&quot;]]</code></pre>

<div class="colab-output">
<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;">0</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;">1</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;">2</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;">福岡</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;">札幌</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;">大阪</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">関西</td>
    </tr>
  </tbody>
</table>
</div>

<p>このように、<strong>「東京なら関東、大阪なら関西」のように対応表がはっきりしている変換</strong>では、<code>apply()</code> より <code>map()</code> の方が読みやすくなります。</p>
<p>一方で、次のように条件や計算が入る場合は、<code>apply()</code> の方が自然に書けることがあります。</p>
<ul>
  <li>点数に応じてラベルを分ける</li>
  <li>購入金額に応じてランクを作る</li>
  <li>複数列を見て判定する</li>
</ul>
<p><code>apply()</code> と <code>map()</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>map()</code></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;"><code>apply()</code></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;"><code>apply(axis=1)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">複数列を見て1行ずつ判定する</td>
    </tr>
  </tbody>
</table>
<p>辞書で値を変換する基本は、別記事の「pandas map()の使い方」で詳しく学ぶと理解しやすいです。</p>

<h2><span id="toc8">4. replace()・astype()・np.where()との使い分け</span></h2>
<p><code>apply()</code> は便利ですが、値の置換や型変換まで全部 <code>apply()</code> で書く必要はありません。</p>
<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>
      <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;"><code>&quot;Tokyo&quot;</code> を <code>&quot;東京&quot;</code> にする</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</code></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;">文字列の数値を <code>int</code> にする</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>astype()</code></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;"><code>&quot;2026-05-04&quot;</code> を日付型にする</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>to_datetime()</code></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;">80点以上なら合格</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>np.where()</code> または <code>apply()</code></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>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>apply(axis=1)</code></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>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>apply()</code></td>
    </tr>
  </tbody>
</table>
<p>ここで大切なのは、<code>apply()</code> を「何でもできる道具」として使いすぎないことです。 処理の目的がはっきりしている場合は、専用のメソッドを優先すると、あとで読み返しやすくなります。</p>

<h2><span id="toc9">5. np.where()との違い：2択だけならnp.where()も使える</span></h2>
<p>単純な2択の条件分岐なら、<code>apply()</code> だけでなく <code>np.where()</code> でも書けます。</p>
<p>たとえば、80点以上なら「合格」、それ以外なら「再確認」とするだけなら、次のように書けます。</p>

<pre class="line-numbers"><code class="language-python">import numpy as np

df[&quot;判定_npwhere&quot;] = np.where(df[&quot;点数&quot;] &gt;= 80, &quot;合格&quot;, &quot;再確認&quot;)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;判定&quot;, &quot;判定_npwhere&quot;]]</code></pre>

<div class="colab-output">
<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;">判定_npwhere</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;">82</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;">59</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;">74</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;">91</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;">66</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;">88</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>
</div>

<p><code>np.where()</code> は、条件が1つで結果が2択のときに短く書けます。</p>
<p>一方で、条件が複数ある場合や、処理の意味を関数名として残したい場合は、自作関数と <code>apply()</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>np.where()</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">条件が1つで、結果が2択のとき</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>apply()</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>apply(axis=1)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">複数列を見て1行ずつ判定したいとき</td>
    </tr>
  </tbody>
</table>
<p>この記事では、<code>np.where()</code> を深く扱いすぎず、<code>apply()</code> を使う判断材料として軽く押さえます。</p>

<h2><span id="toc10">6. DataFrame.apply()とaxis=0・axis=1の違い</span></h2>
<p>ここからは、<code>DataFrame.apply()</code> を見ていきます。</p>
<p><code>DataFrame.apply()</code> では、<code>axis</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;"><code>axis=0</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>axis=1</code></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>
  </tbody>
</table>
<p>特に <code>axis=1</code> は、初心者がつまずきやすいポイントです。 「横方向に処理する」と覚えるより、<strong>1行ずつ処理する</strong>と考える方がわかりやすいです。</p>
<h3><span id="toc11">axisのイメージ</span></h3>
<p><code>axis</code> は、DataFrameをどの向きで処理するかを指定する引数です。 最初は少し混乱しやすいので、次のようにイメージすると整理しやすくなります。</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>
      <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>axis=0</code></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;"><code>axis=1</code></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;">複数列を見て1行ずつ判定する</td>
    </tr>
  </tbody>
</table>
<p>たとえば、<code>axis=0</code> は「国語列」「数学列」のように列単位で処理します。 一方、<code>axis=1</code> は「1人目の国語と数学」「2人目の国語と数学」のように、1行分の複数列をまとめて見ます。</p>
<p>つまり、<strong>複数列を使って新しい列を作りたいときは <code>apply(axis=1)</code> が候補</strong>になります。</p>
<p>まずは、小さな点数表で確認します。</p>

<pre class="line-numbers"><code class="language-python">scores = pd.DataFrame({
    &quot;国語&quot;: [80, 60, 90],
    &quot;数学&quot;: [70, 75, 85]
})

scores</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">80</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">70</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;">60</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">75</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;">90</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">85</td>
    </tr>
  </tbody>
</table>
</div>

<p><code>axis=0</code> を指定すると、列ごとに処理します。 次の例では、各科目の平均点を計算しています。</p>

<pre class="line-numbers"><code class="language-python">scores.apply(lambda col: col.mean(), axis=0)</code></pre>

<div class="colab-output">
<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;">76.66666666666667</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;">76.66666666666667</td>
    </tr>
  </tbody>
</table>
</div>

<p>一方、<code>axis=1</code> を指定すると、行ごとに処理します。 次の例では、各人の平均点を計算しています。</p>

<pre class="line-numbers"><code class="language-python">scores.apply(lambda row: row.mean(), axis=1)</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">75.0</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;">67.5</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;">87.5</td>
    </tr>
  </tbody>
</table>
</div>

<p>この違いを理解すると、<code>apply(axis=1)</code> がなぜ複数列を使う処理で登場するのかが見えてきます。</p>
<ul>
  <li>列ごとに処理したい → <code>axis=0</code></li>
  <li>1行ずつ複数列を見たい → <code>axis=1</code></li>
</ul>
<p>実務では、<code>axis=1</code> は「年齢と購入金額を見て顧客区分を作る」「点数と出席率を見てフォロー対象を判定する」ような場面で使います。</p>

<h2><span id="toc12">7. apply(axis=1)で複数列を見て新しい列を作る</span></h2>
<p>次に、複数列を見て1行ずつ判定する例です。</p>
<p>ここでは、<code>点数</code> と <code>出席率</code> を見て、学習フォローの区分を作ります。</p>
<ul>
  <li>点数が80点以上、かつ出席率が0.8以上なら「順調」</li>
  <li>点数が70点未満、または出席率が0.75未満なら「要フォロー」</li>
  <li>それ以外は「通常」</li>
</ul>
<p>このように、複数列を見て判定したい場合は、<code>apply(axis=1)</code> が候補になります。</p>

<pre class="line-numbers"><code class="language-python">def follow_status(row):
    if row[&quot;点数&quot;] &gt;= 80 and row[&quot;出席率&quot;] &gt;= 0.8:
        return &quot;順調&quot;
    elif row[&quot;点数&quot;] &lt; 70 or row[&quot;出席率&quot;] &lt; 0.75:
        return &quot;要フォロー&quot;
    else:
        return &quot;通常&quot;

df[&quot;学習フォロー&quot;] = df.apply(follow_status, axis=1)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;出席率&quot;, &quot;学習フォロー&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">82</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.95</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;">59</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.7</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;">74</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.82</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;">91</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.98</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;">66</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.6</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;">88</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">0.9</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">順調</td>
    </tr>
  </tbody>
</table>
</div>

<p>この例では、関数の引数 <code>row</code> に、DataFrameの1行分のデータが入ります。 そのため、<code>row[&quot;点数&quot;]</code> や <code>row[&quot;出席率&quot;]</code> のように、同じ行の複数列を参照できます。</p>
<p>これが、<code>Series.apply()</code> と <code>DataFrame.apply(axis=1)</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;"><code>df[&quot;点数&quot;].apply(...)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1列の値</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>df.apply(..., axis=1)</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">1行分のデータ</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">点数と出席率を見て判定する</td>
    </tr>
  </tbody>
</table>

<h2><span id="toc13">8. 処理前→処理後で変化を確認する</span></h2>
<p><code>apply()</code> で新しい列を作るときは、処理前と処理後を確認すると理解しやすくなります。</p>
<p>今回の例では、もともと <code>点数</code> と <code>出席率</code> だけがありました。 そこに、<code>apply(axis=1)</code> で <code>学習フォロー</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;"><code>点数</code>、<code>出席率</code></td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">2つの列を1行ずつ見て判定</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>学習フォロー</code> 列を追加</td>
    </tr>
    <tr>
      <td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">82、0.95</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;">59、0.70</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>
<p><code>apply()</code> の結果を新しい列として保存すると、あとで <code>value_counts()</code> や <code>groupby()</code> にもつなげやすくなります。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;学習フォロー&quot;].value_counts()</code></pre>

<div class="colab-output">
<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;">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>
</div>

<p>このように、<code>apply()</code> は列を作って終わりではありません。 作成した列を使って件数を数えたり、グループ別に集計したりすることで、分析に進みやすくなります。</p>

<h2><span id="toc14">9. 購入金額と年齢から顧客区分を作る</span></h2>
<p>もう1つ、前処理らしい例を見てみましょう。</p>
<p>ここでは、<code>購入金額</code> と <code>年齢</code> を使って、顧客区分を作ります。</p>
<ul>
  <li>購入金額が50,000円以上、かつ年齢が30歳以上なら「重点顧客」</li>
  <li>購入金額が30,000円以上なら「見込み顧客」</li>
  <li>それ以外は「通常顧客」</li>
</ul>
<p>このような独自ルールは、<code>replace()</code> や <code>astype()</code> では書きにくいため、<code>apply(axis=1)</code> が向いています。</p>

<pre class="line-numbers"><code class="language-python">def customer_type(row):
    if row[&quot;購入金額&quot;] &gt;= 50000 and row[&quot;年齢&quot;] &gt;= 30:
        return &quot;重点顧客&quot;
    elif row[&quot;購入金額&quot;] &gt;= 30000:
        return &quot;見込み顧客&quot;
    else:
        return &quot;通常顧客&quot;

df[&quot;顧客区分&quot;] = df.apply(customer_type, axis=1)

df[[&quot;名前&quot;, &quot;年齢&quot;, &quot;購入金額&quot;, &quot;顧客区分&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">22</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</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;">35</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">45000</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;">41</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">28000</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;">29</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">62000</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;">52</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8000</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;">38</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">37000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">見込み顧客</td>
    </tr>
  </tbody>
</table>
</div>

<p>作成した <code>顧客区分</code> は、そのまま集計に使えます。</p>

<pre class="line-numbers"><code class="language-python">df.groupby(&quot;顧客区分&quot;)[&quot;購入金額&quot;].mean()</code></pre>

<div class="colab-output">
<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;">48000.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;">16000.0</td>
    </tr>
  </tbody>
</table>
</div>

<p>この流れは、実際のデータ分析でもよく使います。</p>
<ol>
  <li>元データを確認する</li>
  <li>必要なルールを決める</li>
  <li><code>apply()</code> で区分列を作る</li>
  <li><code>value_counts()</code> や <code>groupby()</code> で集計する</li>
  <li>必要に応じてグラフ化する</li>
</ol>
<p><code>apply()</code> は、前処理と集計をつなぐ中間の役割を持っています。</p>

<h2><span id="toc15">10. apply()の結果が反映されないように見える理由</span></h2>
<p>初心者がよく迷うのが、<code>apply()</code> を実行したのにDataFrameが変わっていないように見えるケースです。</p>
<p><code>apply()</code> は、処理結果を返します。 新しい列として残したい場合は、結果を <code>df[&quot;新しい列&quot;]</code> に代入する必要があります。</p>
<p>⚠️ <strong>注意</strong> <code>apply()</code> の結果を新しい列として残したい場合は、必ず <code>df[&quot;新しい列&quot;] = ...</code> の形で代入します。結果が表示されただけでは、元のDataFrameに保存されたわけではありません。</p>
<p>まずは、代入しない例を見てみます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;購入金額&quot;].apply(lambda x: int(x * 1.1))</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">13200</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;">49500</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;">30800</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;">68200</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;">8800</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;">40700</td>
    </tr>
  </tbody>
</table>
</div>

<p>上のコードを実行すると、税込金額の結果は表示されます。 しかし、これだけでは <code>df</code> に新しい列は追加されません。</p>
<p>新しい列として保存したい場合は、次のように代入します。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;税込金額&quot;] = df[&quot;購入金額&quot;].apply(lambda x: int(x * 1.1))

df[[&quot;名前&quot;, &quot;購入金額&quot;, &quot;税込金額&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">13200</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;">45000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">49500</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;">28000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30800</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;">62000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">68200</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8800</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;">37000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40700</td>
    </tr>
  </tbody>
</table>
</div>

<p>このように、<code>apply()</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;">結果を一時的に確認したい</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>df[&quot;列&quot;].apply(...)</code></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;"><code>df[&quot;新しい列&quot;] = df[&quot;列&quot;].apply(...)</code></td>
    </tr>
  </tbody>
</table>
<p>なお、税込金額のような単純な四則演算だけなら、実務では <code>apply()</code> を使わずに列同士の計算で書く方がシンプルな場合もあります。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;税込金額_直接計算&quot;] = (df[&quot;購入金額&quot;] * 1.1).astype(int)

df[[&quot;名前&quot;, &quot;購入金額&quot;, &quot;税込金額&quot;, &quot;税込金額_直接計算&quot;]]</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">12000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">13200</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">13200</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;">45000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">49500</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">49500</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;">28000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30800</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">30800</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;">62000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">68200</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">68200</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;">8000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8800</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">8800</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;">37000</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40700</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">40700</td>
    </tr>
  </tbody>
</table>
</div>

<p>この例のように、単純な計算なら <code>apply()</code> より列同士の直接計算の方が読みやすいことがあります。 <code>apply()</code> は便利ですが、常に最初の選択肢にする必要はありません。</p>

<h2><span id="toc16">11. 欠損値があるときの注意点</span></h2>
<p><code>apply()</code> では、欠損値がある列を処理するときにも注意が必要です。</p>
<p>たとえば、点数が未入力のデータがあるとします。 このような場合に、何も考えずに比較処理を書くと、意図しない結果になることがあります。</p>
<p>ここでは、点数が未入力の場合は「未確認」と返すようにします。</p>

<pre class="line-numbers"><code class="language-python">df_missing = pd.DataFrame({
    &quot;名前&quot;: [&quot;田中&quot;, &quot;佐藤&quot;, &quot;鈴木&quot;],
    &quot;点数&quot;: [82, None, 68]
})

def safe_score_label(score):
    if pd.isna(score):
        return &quot;未確認&quot;
    elif score &gt;= 80:
        return &quot;高得点&quot;
    elif score &gt;= 70:
        return &quot;標準&quot;
    else:
        return &quot;要復習&quot;

df_missing[&quot;点数区分&quot;] = df_missing[&quot;点数&quot;].apply(safe_score_label)

df_missing</code></pre>

<div class="colab-output">
<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;">0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">田中</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">82.0</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;">nan</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;">68.0</td>
      <td style="white-space: nowrap; padding: 0.2em 0.4em;">要復習</td>
    </tr>
  </tbody>
</table>
</div>

<p>欠損値を含む列では、<code>pd.isna()</code> で未入力を確認してから処理すると安全です。</p>
<p>ただし、欠損値をどう扱うべきかはデータの意味によって変わります。 単純に0で埋めればよいとは限らないため、欠損値処理は <code>fillna()</code> や <code>dropna()</code> の考え方と合わせて整理するとよいです。</p>

<h2><span id="toc17">12. apply()でよくあるミス</span></h2>
<p>ここでは、初心者がつまずきやすいポイントを整理します。</p>
<h3><span id="toc18">ミス1：axis=1を付け忘れる</span></h3>
<p>複数列を見て1行ずつ処理したいのに、<code>axis=1</code> を付け忘れると、想定通りに動かないことがあります。</p>
<pre><code class="language-python"># 複数列を1行ずつ見たいなら axis=1 が必要
df.apply(customer_type, axis=1)</code></pre>
<p><code>axis=1</code> は、「1行ずつ処理する」と覚えると迷いにくいです。</p>
<h3><span id="toc19">ミス2：apply()の結果を代入していない</span></h3>
<p>次のように書くと、結果は表示されますが、DataFrameには保存されません。</p>
<pre><code class="language-python">df[&quot;購入金額&quot;].apply(lambda x: int(x * 1.1))</code></pre>
<p>列として残したい場合は、次のように代入します。</p>
<pre><code class="language-python">df[&quot;税込金額&quot;] = df[&quot;購入金額&quot;].apply(lambda x: int(x * 1.1))</code></pre>
<h3><span id="toc20">ミス3：lambdaに条件を書きすぎる</span></h3>
<p><code>lambda</code> は短い処理には便利ですが、条件が長くなると読みにくくなります。</p>
<pre><code class="language-python"># 読みにくくなりやすい例
df[&quot;区分&quot;] = df[&quot;点数&quot;].apply(lambda x: &quot;高得点&quot; if x &gt;= 80 else &quot;標準&quot; if x &gt;= 70 else &quot;要復習&quot;)</code></pre>
<p>このような場合は、自作関数に分ける方が読みやすくなります。</p>
<h3><span id="toc21">ミス4：apply()を何でも使ってしまう</span></h3>
<p><code>apply()</code> は便利ですが、単純な計算や型変換まで <code>apply()</code> にすると、かえって読みづらくなることがあります。</p>
<ul>
  <li>単純な計算 → 列同士の計算</li>
  <li>辞書で変換 → <code>map()</code></li>
  <li>値の置換 → <code>replace()</code></li>
  <li>型変換 → <code>astype()</code> や <code>to_datetime()</code></li>
</ul>
<p>このように、処理の目的に合う方法を選びましょう。</p>

<h2><span id="toc22">13. apply()は遅い？初心者が知っておきたい範囲</span></h2>
<p><code>apply()</code> は便利ですが、大量データでは処理が遅くなることがあります。</p>
<p>ただし、初心者の段階では、最初から速度ばかり気にしすぎる必要はありません。 まずは、次の順番で考えるとよいです。</p>
<ol>
  <li>処理の意味が自分で説明できるか</li>
  <li><code>map()</code>、<code>replace()</code>、<code>astype()</code> など、より目的に合う方法がないか</li>
  <li>単純な計算なら、列同士の計算で書けないか</li>
  <li>それでも関数適用が必要なら <code>apply()</code> を使う</li>
</ol>
<p>たとえば、税込金額のように <code>df[&quot;購入金額&quot;] * 1.1</code> で書ける処理は、<code>apply()</code> よりも列同士の計算で書く方がシンプルです。 まずは「列同士の計算で書けないか」を確認し、それでも自作関数が必要なときに <code>apply()</code> を使うと整理しやすくなります。</p>
<p>巨大データの高速化、NumPyを使った最適化、<code>groupby.apply()</code> の高度な使い方は、この記事では深入りしません。 まずは、<code>apply()</code> の基本と使いどころを理解することを優先しましょう。</p>

<h2><span id="toc23">まとめ</span></h2>
<p>この記事では、<code>pandas apply()</code> の使い方を、初心者向けに解説しました。</p>
<p>大切なポイントは次の通りです。</p>
<ul>
  <li><code>apply()</code> は、関数を列や行にまとめて適用したいときに使う</li>
  <li>1列だけに使う場合は <code>df[&quot;列&quot;].apply(...)</code></li>
  <li>複数列を見て1行ずつ処理したい場合は <code>df.apply(..., axis=1)</code></li>
  <li><code>axis=1</code> は「1行ずつ処理する」と考えるとわかりやすい</li>
  <li>短い処理は <code>lambda</code>、複雑な条件は自作関数に分けると読みやすい</li>
  <li>1列の対応表変換なら <code>map()</code>、値の置換なら <code>replace()</code>、型変換なら <code>astype()</code> を優先する</li>
  <li>単純な2択の条件分岐なら <code>np.where()</code>、複数条件や自作ルールなら <code>apply()</code> を検討する</li>
  <li><code>apply()</code> の結果を列として残したい場合は、<code>df[&quot;新しい列&quot;] = ...</code> のように代入する</li>
  <li><code>apply()</code> で作った列は、<code>value_counts()</code> や <code>groupby()</code> による集計につなげやすい</li>
</ul>
<p><code>apply()</code> は、Pandasの前処理でよく使う便利な道具です。 ただし、この記事の中心は「列追加そのもの」ではなく、関数の結果を列や行に適用する考え方です。 ただし、何でも <code>apply()</code> にするのではなく、「関数を適用する必要があるか」「ほかのメソッドの方が自然ではないか」を考えながら使うと、読みやすいコードになります。</p>

<h2><span id="toc24">次に読みたい関連記事</span></h2>
<p>この記事とあわせて読むと、Pandasの前処理から集計までの流れが理解しやすくなります。</p>
<ul>
  <li><a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門｜作り方・基本操作をわかりやすく解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-map/">pandas map()の使い方｜辞書で値を変換・新しい列を作る方法を初心者向けに解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-add-column/">pandasで新しい列を追加する方法｜df[‘列名’]・assign・条件付き列追加を初心者向けに解説</a></li>  <li><a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方｜文字列・数値への型変換とエラー対処を初心者向けに解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-filtering/">pandas 条件抽出（filtering）入門｜AND/OR・query関数・複数条件の指定方法</a></li>
  <li><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
  <li><a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方｜基本の集計とaggの書き方を例で解説</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="toc25"> カテゴリから探す</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>
</div>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1777886821347" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">pandas apply()は何に使いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>apply()</code> は、Pandasの列や行に関数をまとめて適用したいときに使います。 たとえば、点数から判定列を作る、購入金額から顧客区分を作る、複数列を見て1行ずつ判定する、といった場面で役立ちます。</p>

</div>
</div>
<div id="faq-question-1777886832778" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">apply()とmap()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>map()</code> は、主に1列の値を対応表で変換するときに使います。 一方、<code>apply()</code> は、関数を使って値を加工したいときや、複数列を見て行ごとに判定したいときに使います。</p>

</div>
</div>
<div id="faq-question-1777886844339" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">apply(axis=1)とはどういう意味ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>apply(axis=1)</code> は、DataFrameを1行ずつ処理する指定です。 複数列を見て新しい列を作りたいときに使います。たとえば、<code>点数</code> と <code>出席率</code> を見て「順調」「要フォロー」を判定するような場面です。</p>

</div>
</div>
<div id="faq-question-1777886861361" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc29">lambdaを使わずにapply()は使えますか？</span></h3>
<div class="rank-math-answer ">

<p>使えます。 <code>lambda</code> の代わりに、自分で定義した関数を <code>apply()</code> に渡せます。条件が複数ある場合や、あとで読み返しやすくしたい場合は、自作関数に分けるのがおすすめです。</p>

</div>
</div>
<div id="faq-question-1777886868124" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">apply()で新しい列を作れますか？</span></h3>
<div class="rank-math-answer ">

<p>作れます。 たとえば、<code>df["新しい列"] = df["元の列"].apply(関数)</code> のように書くと、処理結果を新しい列として保存できます。複数列を使う場合は、<code>df["新しい列"] = df.apply(関数, axis=1)</code> のように書きます。</p>

</div>
</div>
<div id="faq-question-1777886878361" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">apply()の結果が元のDataFrameに反映されないのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p><code>apply()</code> の結果を表示しただけでは、元のDataFrameには保存されません。 新しい列として残したい場合は、<code>df["新しい列"] = ...</code> のように代入する必要があります。</p>

</div>
</div>
<div id="faq-question-1777886893819" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">apply()とnp.where()はどちらを使えばよいですか？</span></h3>
<div class="rank-math-answer ">

<p>単純な2択の条件分岐なら <code>np.where()</code> が簡潔です。たとえば、80点以上なら「合格」、それ以外なら「再確認」のような処理です。 一方で、条件が複数ある場合や、自作関数で処理を整理したい場合は <code>apply()</code> が向いています。初心者のうちは、短く書くことよりも、あとで読んで意味がわかることを優先して選ぶとよいです。</p>

</div>
</div>
<div id="faq-question-1777886907082" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">apply()が遅いと言われるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p><code>apply()</code> は、行や値を1つずつ関数に渡して処理するため、大量データでは遅くなることがあります。 単純な計算なら列同士の計算、辞書変換なら <code>map()</code>、値の置換なら <code>replace()</code> のように、目的に合った方法を選ぶと読みやすさと効率の両方を保ちやすくなります。</p>

</div>
</div>
<div id="faq-question-1777886924234" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">applymap()やDataFrame.map()もこの記事で扱うべきですか？</span></h3>
<div class="rank-math-answer ">

<p>この記事では、初心者がまず迷いやすい <code>apply()</code>、<code>axis=1</code>、<code>lambda</code>、<code>map()</code> との違いに絞って解説しています。 <code>applymap()</code> や <code>DataFrame.map()</code> は、DataFrame内の各要素に処理を適用する場面で使われますが、最初から広げると混乱しやすいため、この記事では深入りしません。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-apply/">pandas apply()の使い方｜axis=1で行ごとに処理・lambda・mapとの違いを解説</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-apply/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
