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

<channel>
	<title>Pandasデータ抽出・前処理入門｜loc, iloc, isin, dropの使い方まとめ | Python Data Lab（Pythonデータラボ）</title>
	<atom:link href="https://pythondatalab.com/category/pandas/preprocessing/feed/" rel="self" type="application/rss+xml" />
	<link>https://pythondatalab.com</link>
	<description>Python初心者向けに、わかりやすいデータ分析の解説を提供します。</description>
	<lastBuildDate>Sun, 10 May 2026 15:42:09 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://pythondatalab.com/wp-content/uploads/2025/12/cropped-rogo-32x32.png</url>
	<title>Pandasデータ抽出・前処理入門｜loc, iloc, isin, dropの使い方まとめ | Python Data Lab（Pythonデータラボ）</title>
	<link>https://pythondatalab.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-1" checked><label class="toc-title" for="toc-checkbox-1">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">やりたいこと別：between()を使う場面</a></li><li><a href="#toc3" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc4" tabindex="0">数値を範囲で抽出する方法</a><ol><li><a href="#toc5" tabindex="0">まずbetween()で範囲内かどうかを判定する</a></li><li><a href="#toc6" tabindex="0">判定結果を使って行を抽出する</a></li></ol></li><li><a href="#toc7" tabindex="0">日付を範囲で抽出する方法</a></li><li><a href="#toc8" tabindex="0">inclusiveで数値や日付の範囲の境界値を含める・含めない設定</a></li><li><a href="#toc9" tabindex="0">範囲抽出で欠損値があるときの注意点</a></li><li><a href="#toc10" tabindex="0">between()と&gt;=・&lt;=・query()・cut()の違い</a><ol><li><a href="#toc11" tabindex="0">query()で書く場合</a></li><li><a href="#toc12" tabindex="0">cut()は抽出ではなく分類に使う</a></li><li><a href="#toc13" tabindex="0">between()を使わない場面も確認しておく</a></li></ol></li><li><a href="#toc14" tabindex="0">抽出したデータを集計して確認する</a><ol><li><a href="#toc15" tabindex="0">必要に応じてグラフで確認する</a></li></ol></li><li><a href="#toc16" tabindex="0">よくあるミスと確認ポイント</a></li><li><a href="#toc17" tabindex="0">between()は前処理・抽出で使う</a></li><li><a href="#toc18" tabindex="0">まとめ：between()は数値・日付の範囲抽出を読みやすくする方法</a></li><li><a href="#toc19" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc20" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc21" tabindex="0">pandasのbetween()は何をするメソッドですか？</a></li><li><a href="#toc22" tabindex="0">between()は境界値を含みますか？</a></li><li><a href="#toc23" tabindex="0">between()で日付の範囲抽出はできますか？</a></li><li><a href="#toc24" tabindex="0">between()と&gt;=・&lt;=は何が違いますか？</a></li><li><a href="#toc25" tabindex="0">between()とquery()はどちらを使えばよいですか？</a></li><li><a href="#toc26" tabindex="0">between()とcut()は何が違いますか？</a></li><li><a href="#toc27" tabindex="0">範囲抽出で欠損値があるとき、between()はどうなりますか？</a></li><li><a href="#toc28" tabindex="0">文字列の数字にbetween()を使ってもよいですか？</a></li></ol></li></ol>
    </div>
  </div>

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



  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2" checked><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">まずdtypesで型を確認してからselect_dtypes()を使う</a></li><li><a href="#toc3" tabindex="0">select_dtypes()とは？</a></li><li><a href="#toc4" tabindex="0">まずはサンプルデータを作る</a></li><li><a href="#toc5" tabindex="0">まずは変換前のデータで数値列だけを選んでみる</a></li><li><a href="#toc6" tabindex="0">売上を数値型に変換する</a></li><li><a href="#toc7" tabindex="0">変換後に数値列だけを選ぶ：include=&#8221;number&#8221;</a></li><li><a href="#toc8" tabindex="0">文字列が入っている列だけを選ぶ：include=[&#8220;object&#8221;, &#8220;string&#8221;]</a></li><li><a href="#toc9" tabindex="0">object型を選ぶときの注意</a></li><li><a href="#toc10" tabindex="0">日付列だけを選ぶ：include=&#8221;datetime&#8221;</a></li><li><a href="#toc11" tabindex="0">補足：category列やbool列も選べる</a></li><li><a href="#toc12" tabindex="0">excludeで特定の型を除外する</a></li><li><a href="#toc13" tabindex="0">select_dtypes()で次の処理に進みやすくする</a></li><li><a href="#toc14" tabindex="0">まとめ</a><ol><li><a href="#toc15" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc16" tabindex="0">pandasで数値列だけ抽出するにはどうすればよいですか？</a></li><li><a href="#toc17" tabindex="0">pandasで文字列が入っている列だけ選ぶにはどうすればよいですか？</a></li><li><a href="#toc18" tabindex="0">日付列だけを選ぶことはできますか？</a></li><li><a href="#toc19" tabindex="0">select_dtypes()で型は変換できますか？</a></li><li><a href="#toc20" tabindex="0">うまく列が選ばれないときは何を確認すればよいですか？</a></li><li><a href="#toc21" tabindex="0">includeとexcludeを同時に使うときの注意はありますか？</a></li></ol></li></ol>
    </div>
  </div>

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

  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-3" checked><label class="toc-title" for="toc-checkbox-3">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">Pandas前処理の中での位置づけ</a></li><li><a href="#toc3" tabindex="0">まず結論：to_numeric()は「計算できる数値」に変換するために使う</a></li><li><a href="#toc4" tabindex="0">数字に見えるのに計算できない例</a></li><li><a href="#toc5" tabindex="0">to_numeric()の基本的な使い方</a><ol><li><a href="#toc6" tabindex="0">複数列をまとめて数値に変換したい場合</a></li></ol></li><li><a href="#toc7" tabindex="0">処理前後で見る：文字列の数字が数値になる</a></li><li><a href="#toc8" tabindex="0">変換できない値が混ざるとエラーになる</a></li><li><a href="#toc9" tabindex="0">errors=&#8221;coerce&#8221;で変換できない値をNaNにする</a></li><li><a href="#toc10" tabindex="0">NaNになった行を確認する</a></li><li><a href="#toc11" tabindex="0">errorsの違いを軽く整理する</a></li><li><a href="#toc12" tabindex="0">to_numeric()とastype()の違い</a></li><li><a href="#toc13" tabindex="0">カンマ入り数値や「円」付きの金額を数値化する</a></li><li><a href="#toc14" tabindex="0">変換後のNaNをどう扱うか</a></li><li><a href="#toc15" tabindex="0">数値化できると集計や可視化に進みやすくなる</a><ol><li><a href="#toc16" tabindex="0">補足：グラフを日本語表示したい場合</a></li></ol></li><li><a href="#toc17" tabindex="0">すべてのobject型を数値化すればよいわけではない</a></li><li><a href="#toc18" tabindex="0">よくあるミスと確認ポイント</a></li><li><a href="#toc19" tabindex="0">まとめ</a></li><li><a href="#toc20" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc21" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc22" tabindex="0"> to_numeric()とastype()は何が違いますか？</a></li><li><a href="#toc23" tabindex="0">errors=&#8221;coerce&#8221;とは何ですか？</a></li><li><a href="#toc24" tabindex="0">to_numeric()でNaNになるのはなぜですか？</a></li><li><a href="#toc25" tabindex="0">カンマ入りの「1,000」はそのまま数値にできますか？</a></li><li><a href="#toc26" tabindex="0">「円」が付いた金額はどうすればよいですか？</a></li><li><a href="#toc27" tabindex="0">read_csvで読み込んだ列がobject型になるのはなぜですか？</a></li></ol></li></ol>
    </div>
  </div>

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


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-4" checked><label class="toc-title" for="toc-checkbox-4">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">Excelファイルを読み込んだ後の流れ</a></li><li><a href="#toc3" tabindex="0">read_excel()とは？</a></li><li><a href="#toc4" tabindex="0">Google Colabで自分のExcelファイルを読み込む場合</a></li><li><a href="#toc5" tabindex="0">練習用のExcelファイルを用意する</a></li><li><a href="#toc6" tabindex="0">まずは基本形でExcelファイルを読み込む</a></li><li><a href="#toc7" tabindex="0">sheet_nameで読み込むシートを指定する</a></li><li><a href="#toc8" tabindex="0">usecolsで必要な列だけ読み込む</a></li><li><a href="#toc9" tabindex="0">headerとskiprowsで見出し行のズレを調整する</a><ol><li><a href="#toc10" tabindex="0">headerで「列名として使う行」を指定する</a></li><li><a href="#toc11" tabindex="0">skiprowsで「読み飛ばす行」を指定する</a></li></ol></li><li><a href="#toc12" tabindex="0">index_colは必要な場合だけ使う</a></li><li><a href="#toc13" tabindex="0">read_excel()とread_csv()の違い</a></li><li><a href="#toc14" tabindex="0">ExcelをCSVに変換してから扱ったほうがよい場合</a></li><li><a href="#toc15" tabindex="0">よくあるミスとエラー対処</a><ol><li><a href="#toc16" tabindex="0">read_csv()でExcelファイルを読もうとしてしまう</a></li><li><a href="#toc17" tabindex="0">sheet_nameを列名だと思ってしまう</a></li><li><a href="#toc18" tabindex="0">usecolsで行を絞ろうとしてしまう</a></li><li><a href="#toc19" tabindex="0">openpyxlが必要というエラーが出る</a></li></ol></li><li><a href="#toc20" tabindex="0">読み込んだ後は前処理につなげる</a></li><li><a href="#toc21" tabindex="0">read_excel()で押さえるポイントを整理する</a></li><li><a href="#toc22" tabindex="0">まとめ</a></li><li><a href="#toc23" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc24" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc25" tabindex="0">pandasでExcelファイルを読み込むにはどうすればよいですか？</a></li><li><a href="#toc26" tabindex="0">read_excel()とread_csv()の違いは何ですか？</a></li><li><a href="#toc27" tabindex="0">Excelの複数シートを読み込むにはどうすればよいですか？</a></li><li><a href="#toc28" tabindex="0">特定の列だけ読み込むにはどうすればよいですか？</a></li><li><a href="#toc29" tabindex="0">1行目が見出しではないExcelはどう読み込めばよいですか？</a></li><li><a href="#toc30" tabindex="0">列名を自分で付けたい場合はどうすればよいですか？</a></li><li><a href="#toc31" tabindex="0">openpyxlが必要というエラーが出たらどうすればよいですか？</a></li><li><a href="#toc32" tabindex="0">読み込んだExcelの日付や数値の型がおかしいときはどうすればよいですか？</a></li><li><a href="#toc33" tabindex="0">Excelに保存するにはto_excel()を使えばよいですか？</a></li><li><a href="#toc34" tabindex="0">ExcelはCSVに変換してから扱ったほうがよいですか？</a></li></ol></li></ol>
    </div>
  </div>

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

  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-5" checked><label class="toc-title" for="toc-checkbox-5">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">先に結論：3つのメソッドは目的で使い分ける</a></li><li><a href="#toc2" tabindex="0">この記事でわかること</a></li><li><a href="#toc3" tabindex="0">似たメソッドまで含めた使い分け</a></li><li><a href="#toc4" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc5" tabindex="0">unique()で重複を除いた値の一覧を確認する</a><ol><li><a href="#toc6" tabindex="0">unique()の結果はDataFrameではない</a></li></ol></li><li><a href="#toc7" tabindex="0">nunique()で値の種類数を確認する</a></li><li><a href="#toc8" tabindex="0">unique()とnunique()の違い</a></li><li><a href="#toc9" tabindex="0">value_counts()との違い</a></li><li><a href="#toc10" tabindex="0">欠損値（NaN / &lt;NA&gt;）がある場合の注意点</a></li><li><a href="#toc11" tabindex="0">count()とnunique()の違い</a></li><li><a href="#toc12" tabindex="0">unique()で表記ゆれを見つける</a><ol><li><a href="#toc13" tabindex="0">表記ゆれを軽くそろえてから確認する例</a></li></ol></li><li><a href="#toc14" tabindex="0">groupby().nunique()でグループごとの種類数を確認する</a></li><li><a href="#toc15" tabindex="0">duplicated()やdrop_duplicates()との違い</a></li><li><a href="#toc16" tabindex="0">よくあるミスと注意点</a><ol><li><a href="#toc17" tabindex="0">unique()は元のDataFrameを書き換えない</a></li><li><a href="#toc18" tabindex="0">nunique()は値の一覧ではなく個数を返す</a></li><li><a href="#toc19" tabindex="0">nunique()は標準では欠損値を数えない</a></li><li><a href="#toc20" tabindex="0">value_counts()とは目的が違う</a></li><li><a href="#toc21" tabindex="0">unique()で表記ゆれを見つけても自動では直らない</a></li></ol></li><li><a href="#toc22" tabindex="0">データ分析の流れの中でunique()・nunique()を使うタイミング</a></li><li><a href="#toc23" tabindex="0">まとめ</a></li><li><a href="#toc24" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc25" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc26" tabindex="0">pandasのunique()は何をするメソッドですか？</a></li><li><a href="#toc27" tabindex="0">unique()とnunique()の違いは何ですか？</a></li><li><a href="#toc28" tabindex="0">unique()とvalue_counts()はどう使い分けますか？</a></li><li><a href="#toc29" tabindex="0">nunique()とcount()の違いは何ですか？</a></li><li><a href="#toc30" tabindex="0">nunique()は欠損値を数えますか？</a></li><li><a href="#toc31" tabindex="0">unique()の結果にNaNや&lt;NA&gt;が出るのはなぜですか？</a></li><li><a href="#toc32" tabindex="0">複数列に対してunique()は使えますか？</a></li><li><a href="#toc33" tabindex="0">グループごとにユニーク数を数えるにはどうすればよいですか？</a></li><li><a href="#toc34" tabindex="0">表記ゆれの確認にunique()は使えますか？</a></li><li><a href="#toc35" tabindex="0">DataFrame全体で列ごとの種類数を確認できますか？</a></li></ol></li></ol>
    </div>
  </div>

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


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-6" checked><label class="toc-title" for="toc-checkbox-6">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">まずはこの3行：日付から年・月・曜日を取り出す基本形</a></li><li><a href="#toc2" tabindex="0">この記事でわかること</a></li><li><a href="#toc3" tabindex="0">やりたいこと別：.dtの使い分け早見表</a></li><li><a href="#toc4" tabindex="0">.dtとは？日付列から年・月・曜日を取り出す書き方</a></li><li><a href="#toc5" tabindex="0">to_datetime()と.dtの違い</a></li><li><a href="#toc6" tabindex="0">この処理はどこで使う？日付変換の次に行う前処理</a></li><li><a href="#toc7" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc8" tabindex="0">まずは日付列の型を確認する</a></li><li><a href="#toc9" tabindex="0">.dtを使う前にto_datetime()で日付型に変換する</a></li><li><a href="#toc10" tabindex="0">.dt.yearで日付から年を取り出す</a></li><li><a href="#toc11" tabindex="0">.dt.monthで日付から月を取り出す</a></li><li><a href="#toc12" tabindex="0">.dt.dayで日付から日を取り出す</a></li><li><a href="#toc13" tabindex="0">.dt.day_name()で曜日名を取り出す</a></li><li><a href="#toc14" tabindex="0">.dt.weekdayで曜日番号を取り出す</a></li><li><a href="#toc15" tabindex="0">処理前と処理後を比較する</a></li><li><a href="#toc16" tabindex="0">よく使う.dtの取り出し項目</a></li><li><a href="#toc17" tabindex="0">年月単位で集計したいときはdt.strftime(&quot;%Y-%m&quot;)も使う</a></li><li><a href="#toc18" tabindex="0">月別売上を集計する</a></li><li><a href="#toc19" tabindex="0">曜日別売上を集計する</a></li><li><a href="#toc20" tabindex="0">月別・曜日別に何を見たいかで使い分ける</a></li><li><a href="#toc21" tabindex="0">.dtでよくあるエラーと原因</a></li><li><a href="#toc22" tabindex="0">NaTがある列に.dtを使うとどうなるか</a></li><li><a href="#toc23" tabindex="0">.dtで作った列は新しい列として残すと分析しやすい</a></li><li><a href="#toc24" tabindex="0">可視化につなげるときの考え方</a></li><li><a href="#toc25" tabindex="0">軽く知っておくと便利な.dtの関連機能</a></li><li><a href="#toc26" tabindex="0">まとめ：.dtは日付を分析に使いやすくする前処理</a></li><li><a href="#toc27" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc28" tabindex="0">基礎・CSV読み込み</a></li><li><a href="#toc29" tabindex="0">型確認・日付変換</a></li><li><a href="#toc30" tabindex="0">列追加・集計</a></li><li><a href="#toc31" tabindex="0">可視化</a></li><li><a href="#toc32" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc33" tabindex="0">pandasの.dtとは何ですか？</a></li><li><a href="#toc34" tabindex="0">.dtを使うとエラーになるのはなぜですか？</a></li><li><a href="#toc35" tabindex="0">to_datetime()と.dtは何が違いますか？</a></li><li><a href="#toc36" tabindex="0">日付から年や月だけを取り出すにはどうすればよいですか？</a></li><li><a href="#toc37" tabindex="0">日付から曜日を取得するにはどうすればよいですか？</a></li><li><a href="#toc38" tabindex="0">.dt.weekdayと.dt.day_name()は何が違いますか？</a></li><li><a href="#toc39" tabindex="0">月別集計をするには、.dt.monthだけでよいですか？</a></li><li><a href="#toc40" tabindex="0">NaTがある列に.dtを使っても大丈夫ですか？</a></li></ol></li></ol>
    </div>
  </div>

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


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-7" checked><label class="toc-title" for="toc-checkbox-7">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">データ分析の流れの中でのapply()の位置づけ</a></li><li><a href="#toc3" tabindex="0">先に結論：apply()は「関数を列や行に適用する」ときに使う</a></li><li><a href="#toc4" tabindex="0">サンプルデータを用意する</a></li><li><a href="#toc5" tabindex="0">1. Series.apply()で1列に処理を適用する</a></li><li><a href="#toc6" tabindex="0">2. 自作関数をapply()に渡す</a></li><li><a href="#toc7" tabindex="0">3. map()との違い：対応表があるならmap()が読みやすい</a></li><li><a href="#toc8" tabindex="0">4. replace()・astype()・np.where()との使い分け</a></li><li><a href="#toc9" tabindex="0">5. np.where()との違い：2択だけならnp.where()も使える</a></li><li><a href="#toc10" tabindex="0">6. DataFrame.apply()とaxis=0・axis=1の違い</a><ol><li><a href="#toc11" tabindex="0">axisのイメージ</a></li></ol></li><li><a href="#toc12" tabindex="0">7. apply(axis=1)で複数列を見て新しい列を作る</a></li><li><a href="#toc13" tabindex="0">8. 処理前→処理後で変化を確認する</a></li><li><a href="#toc14" tabindex="0">9. 購入金額と年齢から顧客区分を作る</a></li><li><a href="#toc15" tabindex="0">10. apply()の結果が反映されないように見える理由</a></li><li><a href="#toc16" tabindex="0">11. 欠損値があるときの注意点</a></li><li><a href="#toc17" tabindex="0">12. apply()でよくあるミス</a><ol><li><a href="#toc18" tabindex="0">ミス1：axis=1を付け忘れる</a></li><li><a href="#toc19" tabindex="0">ミス2：apply()の結果を代入していない</a></li><li><a href="#toc20" tabindex="0">ミス3：lambdaに条件を書きすぎる</a></li><li><a href="#toc21" tabindex="0">ミス4：apply()を何でも使ってしまう</a></li></ol></li><li><a href="#toc22" tabindex="0">13. apply()は遅い？初心者が知っておきたい範囲</a></li><li><a href="#toc23" tabindex="0">まとめ</a></li><li><a href="#toc24" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc25" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc26" tabindex="0">pandas apply()は何に使いますか？</a></li><li><a href="#toc27" tabindex="0">apply()とmap()の違いは何ですか？</a></li><li><a href="#toc28" tabindex="0">apply(axis=1)とはどういう意味ですか？</a></li><li><a href="#toc29" tabindex="0">lambdaを使わずにapply()は使えますか？</a></li><li><a href="#toc30" tabindex="0">apply()で新しい列を作れますか？</a></li><li><a href="#toc31" tabindex="0">apply()の結果が元のDataFrameに反映されないのはなぜですか？</a></li><li><a href="#toc32" tabindex="0">apply()とnp.where()はどちらを使えばよいですか？</a></li><li><a href="#toc33" tabindex="0">apply()が遅いと言われるのはなぜですか？</a></li><li><a href="#toc34" tabindex="0">applymap()やDataFrame.map()もこの記事で扱うべきですか？</a></li></ol></li></ol>
    </div>
  </div>

<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>
		<item>
		<title>pandas duplicated()の使い方｜重複行の確認・subset・keepを初心者向けに解説</title>
		<link>https://pythondatalab.com/pandas-duplicated/</link>
					<comments>https://pythondatalab.com/pandas-duplicated/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Mon, 04 May 2026 07:09:59 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2019</guid>

					<description><![CDATA[<p>pandasのduplicated()で重複行を確認する方法を初心者向けに解説。True/Falseの意味、subset、keepの違い、drop_duplicates()との使い分けまで、削除前に安全に確認する流れで紹介します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-duplicated/">pandas duplicated()の使い方｜重複行の確認・subset・keepを初心者向けに解説</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;
    font-size: 16px;
  }
  .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 p {
    margin: 0 0 1em;
  }
  .colab-article ul,
  .colab-article ol {
    margin: 0 0 1em 1.4em;
  }
  .colab-article li {
    margin: 0.25em 0;
  }
  .colab-article code {
    font-family: Consolas, Monaco, "Courier New", monospace;
  }
  .colab-article pre[class*="language-"] {
    margin: 0 0 1em !important;
    padding: 1em;
    overflow-x: auto;
    border-radius: 6px;
  }
  .colab-table-wrap {
    overflow-x: auto;
    margin: 0 0 1.2em;
  }
  .colab-table-wrap table.wp-block-table {
    width: auto;
    border-collapse: collapse;
    font-size: 0.95em;
  }
  .colab-table-wrap table.wp-block-table th,
  .colab-table-wrap table.wp-block-table td {
    border: 1px solid #ddd;
  }
  .colab-table-wrap table.wp-block-table th:first-child,
  .colab-table-wrap table.wp-block-table td:first-child {
    min-width: 3em;
    white-space: nowrap;
    padding: 0.2em 0.4em;
  }
  .colab-table-wrap table.wp-block-table th:not(:first-child),
  .colab-table-wrap table.wp-block-table td:not(:first-child) {
    white-space: nowrap;
    padding: 0.2em 0.4em;
  }
  .colab-output {
    margin: 0 0 1em;
    padding: 0.8em;
    background: #f6f8fa;
    border: 1px solid #e5e7eb;
    overflow-x: auto;
  }
  .colab-error {
    background: #fff5f5;
    border-color: #f5c2c7;
  }
  .colab-figure {
    margin: 1.2em 0;
    text-align: center;
  }
  .colab-figure img {
    max-width: 100%;
    height: auto;
  }
  .colab-figure figcaption {
    font-size: 0.9em;
    color: #666;
    margin-top: 0.4em;
  }
</style>


<div class="colab-article">


<p>CSVファイルを読み込んだあとに、同じ顧客IDや同じ注文番号が何度も出てくることがあります。</p>
<p>そのときに、いきなり重複行を削除してしまうと、本当は残すべき注文データまで消してしまうことがあります。</p>
<p>そこで使うのが、Pandasの <code>duplicated()</code> です。</p>
<p><code>duplicated()</code> は、重複している行を <code>True</code> / <code>False</code> で確認するためのメソッドです。<br />
<code>drop_duplicates()</code> のように重複を削除する前に、「どの行が重複と判定されているのか」を確認するために使います。</p>
<p>この記事では、<code>duplicated()</code> を使って重複行を安全に確認し、削除・集計・結合に進む前に「どのデータを残すべきか」を判断できるようにします。</p>

  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-8" checked><label class="toc-title" for="toc-checkbox-8">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">先に結論</a></li><li><a href="#toc2" tabindex="0">この記事でわかること</a></li><li><a href="#toc3" tabindex="0">Pandas DataFrame入門シリーズでの位置づけ</a></li><li><a href="#toc4" tabindex="0">1. duplicated()とは何か</a></li><li><a href="#toc5" tabindex="0">2. サンプルデータを用意する</a></li><li><a href="#toc6" tabindex="0">3. 行全体の重複を確認する</a><ol><li><a href="#toc7" tabindex="0">処理前→duplicated()結果→重複行だけ抽出の見方</a></li></ol></li><li><a href="#toc8" tabindex="0">4. 重複行だけを抽出する</a></li><li><a href="#toc9" tabindex="0">5. duplicated().sum()で重複件数を確認する</a></li><li><a href="#toc10" tabindex="0">6. subsetで特定の列だけを基準にする</a><ol><li><a href="#toc11" tabindex="0">注文番号だけを基準に重複を確認する</a></li><li><a href="#toc12" tabindex="0">顧客IDだけを見ると、削除してはいけないデータまで重複に見えることがある</a></li><li><a href="#toc13" tabindex="0">顧客IDと注文番号の組み合わせで確認する</a></li></ol></li><li><a href="#toc14" tabindex="0">7. keepの違いを理解する</a><ol><li><a href="#toc15" tabindex="0">同じデータでkeepの3パターンを比較する</a></li></ol></li><li><a href="#toc16" tabindex="0">8. duplicated()とdrop_duplicates()の違い</a><ol><li><a href="#toc17" tabindex="0">削除する前に、まず確認する</a></li></ol></li><li><a href="#toc18" tabindex="0">9. value_counts()やgroupby()との使い分け</a></li><li><a href="#toc19" tabindex="0">削除前チェックリスト：重複行を消す前に確認すること</a></li><li><a href="#toc20" tabindex="0">11. よくあるミスと注意点</a><ol><li><a href="#toc21" tabindex="0">ミス1：duplicated()で重複が削除されると思ってしまう</a></li><li><a href="#toc22" tabindex="0">ミス2：Trueを「残す行」だと思ってしまう</a></li><li><a href="#toc23" tabindex="0">ミス3：名前だけで重複削除しようとする</a></li><li><a href="#toc24" tabindex="0">ミス4：subsetを指定せずに「重複がない」と判断してしまう</a></li><li><a href="#toc25" tabindex="0">ミス5：重複は必ず悪いデータだと思ってしまう</a></li></ol></li><li><a href="#toc26" tabindex="0">12. 前処理の流れの中でduplicated()を使うタイミング</a></li><li><a href="#toc27" tabindex="0">13. まとめ</a></li><li><a href="#toc28" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc29" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc30" tabindex="0">pandas duplicated()は何をするメソッドですか？</a></li><li><a href="#toc31" tabindex="0">duplicated()とdrop_duplicates()の違いは何ですか？</a></li><li><a href="#toc32" tabindex="0">重複行だけを表示するにはどうすればよいですか？</a></li><li><a href="#toc33" tabindex="0">duplicated().sum()は何を数えていますか？</a></li><li><a href="#toc34" tabindex="0">duplicated().sum()は何を数えていますか？</a></li><li><a href="#toc35" tabindex="0">subsetは何のために使いますか？</a></li><li><a href="#toc36" tabindex="0">keep=&#8217;first&#8217;、keep=&#8217;last&#8217;、keep=Falseの違いは何ですか？</a></li><li><a href="#toc37" tabindex="0">重複行は必ず削除したほうがよいですか？</a></li><li><a href="#toc38" tabindex="0">value_counts()とduplicated()はどう使い分けますか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">先に結論</span></h2>
<p><code>duplicated()</code> は、重複行を削除するメソッドではなく、<strong>重複している行を確認するためのメソッド</strong>です。</p>
<p>迷ったら、まず次の流れで確認すると安全です。</p>
<ol>
<li><code>df.duplicated()</code> で重複の有無を見る</li>
<li><code>df[df.duplicated(keep=False)]</code> で重複グループ全体を確認する</li>
<li><code>subset</code> で「どの列を基準に重複と見るか」を決める</li>
<li>本当に削除してよいと判断できたら <code>drop_duplicates()</code> を使う</li>
</ol>
<p>特に初心者のうちは、<strong>重複を見つけること</strong>と<strong>重複を削除すること</strong>を分けて考えるのが大切です。</p>

<h2><span id="toc2">この記事でわかること</span></h2>
<p>この記事では、次の内容を初心者向けに解説します。</p>
<ul>
<li><code>duplicated()</code> で重複行を確認する方法</li>
<li><code>True</code> / <code>False</code> の意味</li>
<li>重複行だけを抽出する方法</li>
<li><code>duplicated().sum()</code> で重複件数を確認する方法</li>
<li><code>subset</code> で特定の列だけを基準にする方法</li>
<li><code>keep='first'</code>、<code>keep='last'</code>、<code>keep=False</code> の違い</li>
<li><code>duplicated()</code> と <code>drop_duplicates()</code> の違い</li>
<li>重複行を削除する前に確認すべきポイント</li>
</ul>
<p>ポイントは、<strong>重複を見つけること</strong>と、<strong>重複を削除すること</strong>を分けて考えることです。</p>

<h2><span id="toc3">Pandas DataFrame入門シリーズでの位置づけ</span></h2>
<p>このテーマは、Pandasの前処理の中でも「データ品質チェック」に近い内容です。</p>
<p>基本的な流れとしては、次のように考えると自然です。</p>
<ol>
<li>CSVを読み込む</li>
<li><code>head()</code>、<code>info()</code>、<code>describe()</code> で全体を確認する</li>
<li><code>isnull()</code> で欠損値を確認する</li>
<li><code>duplicated()</code> で重複行を確認する</li>
<li>必要に応じて <code>drop_duplicates()</code> で削除する</li>
<li><code>value_counts()</code>、<code>groupby()</code>、<code>pivot_table()</code> などで集計する</li>
</ol>
<p>つまり、<code>duplicated()</code> は「削除するためのメソッド」というより、<strong>削除してよいか判断する前の確認メソッド</strong>として使うのが大切です。</p>

<h2><span id="toc4">1. duplicated()とは何か</span></h2>
<p><code>duplicated()</code> は、DataFrameの行が重複しているかどうかを確認するメソッドです。</p>
<p>基本形は次のとおりです。</p>
<pre><code class="language-python">df.duplicated()
</code></pre>
<p>実行すると、各行について <code>True</code> または <code>False</code> が返ります。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>結果</th>
  <th>意味</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>False</code></td>
  <td>その時点では重複扱いされていない行</td>
</tr>
<tr>
  <td><code>True</code></td>
  <td>前に同じ行があり、重複と判定された行</td>
</tr>
</tbody>
</table></div>
<p>ここで注意したいのは、<code>duplicated()</code> は<strong>重複行を削除しない</strong>という点です。<br />
あくまで「この行は重複ですか？」を確認するためのメソッドです。</p>
<p>重複を削除したい場合は、あとで <code>drop_duplicates()</code> を使います。</p>

<h2><span id="toc5">2. サンプルデータを用意する</span></h2>
<p>ここでは、注文データを例にします。</p>
<p>同じ注文番号が2回出てくる行もあれば、同じ顧客が別の商品を注文している行もあります。<br />
初心者が迷いやすいのは、<strong>同じ値があるからといって、必ず削除してよいとは限らない</strong>点です。</p>

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

df = pd.DataFrame({
    &quot;注文番号&quot;: [&quot;A001&quot;, &quot;A002&quot;, &quot;A003&quot;, &quot;A003&quot;, &quot;A004&quot;, &quot;A005&quot;, &quot;A006&quot;, &quot;A006&quot;, &quot;A007&quot;],
    &quot;顧客ID&quot;: [&quot;C001&quot;, &quot;C002&quot;, &quot;C003&quot;, &quot;C003&quot;, &quot;C001&quot;, &quot;C004&quot;, &quot;C005&quot;, &quot;C005&quot;, &quot;C006&quot;],
    &quot;氏名&quot;: [&quot;佐藤&quot;, &quot;鈴木&quot;, &quot;田中&quot;, &quot;田中&quot;, &quot;佐藤&quot;, &quot;高橋&quot;, &quot;伊藤&quot;, &quot;伊藤&quot;, &quot;山田&quot;],
    &quot;商品&quot;: [&quot;ノートPC&quot;, &quot;マウス&quot;, &quot;キーボード&quot;, &quot;キーボード&quot;, &quot;モニター&quot;, &quot;マウス&quot;, &quot;USBメモリ&quot;, &quot;USBメモリ&quot;, &quot;マウス&quot;],
    &quot;金額&quot;: [120000, 2500, 8000, 8000, 30000, 2500, 1500, 1500, 2500],
    &quot;注文日&quot;: [&quot;2026-04-01&quot;, &quot;2026-04-02&quot;, &quot;2026-04-03&quot;, &quot;2026-04-03&quot;, &quot;2026-04-05&quot;, &quot;2026-04-06&quot;, &quot;2026-04-07&quot;, &quot;2026-04-07&quot;, &quot;2026-04-08&quot;]
})

df
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
    </tr>
  </tbody>
</table>
</div>

<p>このデータでは、次のような状態があります。</p>
<ul>
<li><code>A003</code> の注文が2回出ている</li>
<li><code>A006</code> の注文が2回出ている</li>
<li><code>C001</code> の顧客は2回出ているが、注文番号と商品が違う</li>
<li><code>佐藤</code> という名前も2回出ているが、同じ人の別注文として残す可能性がある</li>
</ul>
<p>このように、重複確認では「どの列を基準に重複と見るか」がとても重要です。</p>

<h2><span id="toc6">3. 行全体の重複を確認する</span></h2>
<p>まずは、行全体が同じかどうかを確認します。</p>
<p><code>df.duplicated()</code> を使うと、前に同じ行がある場合に <code>True</code> が返ります。</p>

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

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>False</td>
    </tr>
    <tr>
      <td>3</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>False</td>
    </tr>
    <tr>
      <td>7</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p>この結果だけだと少し見づらいので、元のDataFrameに「重複判定」列を一時的に追加して確認してみましょう。</p>

<pre class="line-numbers"><code class="language-python">df_check = df.copy()
df_check[&quot;重複判定&quot;] = df_check.duplicated()

df_check
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
      <th>重複判定</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>False</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>False</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<h3><span id="toc7">処理前→duplicated()結果→重複行だけ抽出の見方</span></h3>
<p><code>duplicated()</code> を理解するときは、次の3段階で見ると分かりやすいです。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>段階</th>
  <th>確認すること</th>
  <th>使うコード</th>
</tr>
</thead>
<tbody>
<tr>
  <td>処理前</td>
  <td>元データに重複候補があるか</td>
  <td><code>df</code></td>
</tr>
<tr>
  <td>duplicated()結果</td>
  <td>各行が重複扱いかどうか</td>
  <td><code>df.duplicated()</code></td>
</tr>
<tr>
  <td>重複行だけ抽出</td>
  <td><code>True</code> になった行だけを見る</td>
  <td><code>df[df.duplicated()]</code></td>
</tr>
</tbody>
</table></div>
<p>この記事では、いきなり削除せず、まずこの流れで「どの行が重複と判定されているか」を確認します。</p>
<p>特に <code>True</code> は「削除する行」と決めつけるのではなく、<strong>重複候補として確認すべき行</strong>と考えるのが安全です。</p>

<p><code>True</code> になっている行は、前に同じ内容の行があるため「重複」と判定された行です。</p>
<p>ここで大切なのは、<code>False</code> が「絶対に重複していない」という意味ではないことです。<br />
初期設定では、最初に出てきた行は残す前提で <code>False</code> になります。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>判定</th>
  <th>初心者向けの考え方</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>False</code></td>
  <td>最初に出てきた行、または重複していない行</td>
</tr>
<tr>
  <td><code>True</code></td>
  <td>すでに前に同じ行がある行</td>
</tr>
</tbody>
</table></div>
<p>この仕組みは、後で説明する <code>keep='first'</code> と関係しています。</p>

<h2><span id="toc8">4. 重複行だけを抽出する</span></h2>
<p>重複している行だけを見たい場合は、<code>df.duplicated()</code> の結果を条件として使います。</p>
<p>これは条件抽出と同じ考え方です。</p>

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

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
  </tbody>
</table>
</div>

<p>このコードでは、<code>duplicated()</code> が <code>True</code> になった行だけを取り出しています。</p>
<p>つまり、次のような意味です。</p>
<pre><code class="language-python">df[重複している行だけ]
</code></pre>
<p>削除する前に、まずこのように重複行だけを表示して確認すると安全です。</p>

<h2><span id="toc9">5. duplicated().sum()で重複件数を確認する</span></h2>
<p>重複行が何件あるかだけを知りたい場合は、<code>duplicated().sum()</code> を使います。</p>

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

<p><code>duplicated()</code> は <code>True</code> / <code>False</code> を返します。<br />
Pandasでは、<code>True</code> は <code>1</code>、<code>False</code> は <code>0</code> のように数えられるため、<code>.sum()</code> を付けると <code>True</code> の数、つまり重複と判定された行数を確認できます。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>コード</th>
  <th>意味</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>df.duplicated()</code></td>
  <td>各行が重複かどうかを確認する</td>
</tr>
<tr>
  <td><code>df.duplicated().sum()</code></td>
  <td>重複と判定された行数を数える</td>
</tr>
</tbody>
</table></div>
<p>ただし、この件数は「削除すべき件数」とは限りません。<br />
まずは中身を確認してから判断しましょう。</p>
<p>重複グループ全体を確認したい場合は、後で説明する <code>keep=False</code> を使うと、最初の行も含めてまとめて確認できます。</p>

<h2><span id="toc10">6. subsetで特定の列だけを基準にする</span></h2>
<p>ここまでの <code>duplicated()</code> は、行全体が同じかどうかを見ていました。</p>
<p>しかし実務では、行全体ではなく、特定の列だけを基準に重複を確認したいことが多いです。</p>
<p>たとえば、注文データなら次のように考えられます。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>見たいこと</th>
  <th>基準にする列</th>
</tr>
</thead>
<tbody>
<tr>
  <td>同じ注文が重複していないか</td>
  <td><code>注文番号</code></td>
</tr>
<tr>
  <td>同じ顧客が複数回出ているか</td>
  <td><code>顧客ID</code></td>
</tr>
<tr>
  <td>同じ顧客の同じ注文が重複していないか</td>
  <td><code>顧客ID</code> と <code>注文番号</code></td>
</tr>
</tbody>
</table></div>
<p>このようなときに使うのが <code>subset</code> です。</p>

<h3><span id="toc11">注文番号だけを基準に重複を確認する</span></h3>
<p>注文番号が同じなら、同じ注文が二重に入っている可能性があります。<br />
そこで、<code>subset=[&quot;注文番号&quot;]</code> を指定します。</p>

<pre class="line-numbers"><code class="language-python">df_order_check = df.copy()
df_order_check[&quot;注文番号の重複&quot;] = df_order_check.duplicated(subset=[&quot;注文番号&quot;])

df_order_check[[&quot;注文番号&quot;, &quot;顧客ID&quot;, &quot;氏名&quot;, &quot;商品&quot;, &quot;金額&quot;, &quot;注文日&quot;, &quot;注文番号の重複&quot;]]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
      <th>注文番号の重複</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>False</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>False</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p>このように、<code>subset</code> を使うと「行全体」ではなく「指定した列」だけを基準に重複を確認できます。</p>
<p>今回の例では、<code>注文番号</code> が同じ行を重複候補として確認できます。</p>

<h3><span id="toc12">顧客IDだけを見ると、削除してはいけないデータまで重複に見えることがある</span></h3>
<p>次に、<code>顧客ID</code> だけを基準にしてみます。</p>

<pre class="line-numbers"><code class="language-python">df_customer_check = df.copy()
df_customer_check[&quot;顧客IDの重複&quot;] = df_customer_check.duplicated(subset=[&quot;顧客ID&quot;], keep=False)

df_customer_check[[&quot;注文番号&quot;, &quot;顧客ID&quot;, &quot;氏名&quot;, &quot;商品&quot;, &quot;金額&quot;, &quot;注文日&quot;, &quot;顧客IDの重複&quot;]]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
      <th>顧客IDの重複</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
      <td>True</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
      <td>True</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p><code>C001</code> は2回出てきますが、注文番号も商品も違います。<br />
これは同じ顧客が別の商品を注文しているだけかもしれません。</p>
<p>そのため、<code>顧客ID</code> が重複しているからといって、すぐ削除するのは危険です。</p>
<p>重複確認では、次のように考えることが大切です。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>状況</th>
  <th>判断</th>
</tr>
</thead>
<tbody>
<tr>
  <td>同じ注文番号が2回ある</td>
  <td>二重登録の可能性があるため確認する</td>
</tr>
<tr>
  <td>同じ顧客IDが2回ある</td>
  <td>同じ顧客の複数注文かもしれない</td>
</tr>
<tr>
  <td>同じ氏名が2回ある</td>
  <td>同姓同名や同じ顧客の別注文かもしれない</td>
</tr>
<tr>
  <td>行全体が完全に同じ</td>
  <td>重複登録の可能性が高い</td>
</tr>
</tbody>
</table></div>
<p><code>subset</code> は便利ですが、何を基準にするかを間違えると、必要なデータまで削除してしまうことがあります。</p>

<h3><span id="toc13">顧客IDと注文番号の組み合わせで確認する</span></h3>
<p>より安全に確認したい場合は、複数列を <code>subset</code> に指定します。</p>
<p>たとえば、同じ顧客IDで、同じ注文番号の行があるかを確認してみます。</p>

<pre class="line-numbers"><code class="language-python">df_pair_check = df.copy()
df_pair_check[&quot;顧客IDと注文番号の重複&quot;] = df_pair_check.duplicated(subset=[&quot;顧客ID&quot;, &quot;注文番号&quot;], keep=False)

df_pair_check[[&quot;注文番号&quot;, &quot;顧客ID&quot;, &quot;氏名&quot;, &quot;商品&quot;, &quot;金額&quot;, &quot;注文日&quot;, &quot;顧客IDと注文番号の重複&quot;]]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
      <th>顧客IDと注文番号の重複</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p>このように、<code>subset=[&quot;顧客ID&quot;, &quot;注文番号&quot;]</code> とすると、2つの列の組み合わせで重複を確認できます。</p>
<p>初心者のうちは、次の順番で考えると迷いにくいです。</p>
<ol>
<li>まず行全体の重複を見る</li>
<li>次に、注文番号やIDなど、重複の基準になりそうな列を見る</li>
<li>必要なら複数列の組み合わせで確認する</li>
<li>中身を見てから削除するか判断する</li>
</ol>

<h2><span id="toc14">7. keepの違いを理解する</span></h2>
<p><code>duplicated()</code> で初心者が迷いやすいのが、<code>keep</code> です。</p>
<p><code>keep</code> は、重複しているデータのうち、どの行を <code>False</code> として残す扱いにするかを決める引数です。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>指定</th>
  <th>意味</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>keep='first'</code></td>
  <td>最初の行を <code>False</code> にし、2回目以降を <code>True</code> にする</td>
</tr>
<tr>
  <td><code>keep='last'</code></td>
  <td>最後の行を <code>False</code> にし、それより前を <code>True</code> にする</td>
</tr>
<tr>
  <td><code>keep=False</code></td>
  <td>重複している行をすべて <code>True</code> にする</td>
</tr>
</tbody>
</table></div>
<p>初期設定は <code>keep='first'</code> です。</p>

<h3><span id="toc15">同じデータでkeepの3パターンを比較する</span></h3>
<p>注文番号を基準にして、<code>keep='first'</code>、<code>keep='last'</code>、<code>keep=False</code> の違いを見てみましょう。</p>

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

df_keep[&quot;keep_first&quot;] = df_keep.duplicated(subset=[&quot;注文番号&quot;], keep=&quot;first&quot;)
df_keep[&quot;keep_last&quot;] = df_keep.duplicated(subset=[&quot;注文番号&quot;], keep=&quot;last&quot;)
df_keep[&quot;keep_false&quot;] = df_keep.duplicated(subset=[&quot;注文番号&quot;], keep=False)

df_keep[[&quot;注文番号&quot;, &quot;顧客ID&quot;, &quot;氏名&quot;, &quot;商品&quot;, &quot;keep_first&quot;, &quot;keep_last&quot;, &quot;keep_false&quot;]]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>keep_first</th>
      <th>keep_last</th>
      <th>keep_false</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>False</td>
      <td>False</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>False</td>
      <td>False</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>False</td>
      <td>True</td>
      <td>True</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>True</td>
      <td>False</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>False</td>
      <td>False</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>False</td>
      <td>False</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>False</td>
      <td>True</td>
      <td>True</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>True</td>
      <td>False</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>False</td>
      <td>False</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p>結果を見ると、同じ注文番号でも <code>keep</code> の指定によって <code>True</code> になる行が変わることが分かります。</p>
<p>初心者におすすめなのは、重複グループ全体を見たいときに <code>keep=False</code> を使うことです。</p>

<pre class="line-numbers"><code class="language-python">df[df.duplicated(subset=[&quot;注文番号&quot;], keep=False)]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
  </tbody>
</table>
</div>

<p><code>keep=False</code> を使うと、重複している注文番号の行をまとめて確認できます。</p>
<p>削除する前に、</p>
<ul>
<li>どちらを残すべきか</li>
<li>本当に完全な二重登録なのか</li>
<li>金額や注文日が違っていないか</li>
</ul>
<p>を確認しやすくなります。</p>

<h2><span id="toc16">8. duplicated()とdrop_duplicates()の違い</span></h2>
<p><code>duplicated()</code> とよく似た名前のメソッドに、<code>drop_duplicates()</code> があります。</p>
<p>この2つは役割が違います。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>メソッド</th>
  <th>役割</th>
  <th>使う場面</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>duplicated()</code></td>
  <td>重複している行を <code>True</code> / <code>False</code> で確認する</td>
  <td>削除前に確認したいとき</td>
</tr>
<tr>
  <td><code>drop_duplicates()</code></td>
  <td>重複行を削除したDataFrameを返す</td>
  <td>確認後に削除したいとき</td>
</tr>
</tbody>
</table></div>
<p>この記事の中心は、<code>duplicated()</code> による確認です。<br />
<code>drop_duplicates()</code> は、重複を確認したあとに必要なら使います。</p>

<h3><span id="toc17">削除する前に、まず確認する</span></h3>
<p>たとえば、注文番号が重複している行を確認するなら、まず次のようにします。</p>

<pre class="line-numbers"><code class="language-python">df[df.duplicated(subset=[&quot;注文番号&quot;], keep=False)]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
  </tbody>
</table>
</div>

<p>中身を確認して、本当に削除してよいと判断できたら、次に <code>drop_duplicates()</code> を検討します。</p>

<pre class="line-numbers"><code class="language-python">df.drop_duplicates(subset=[&quot;注文番号&quot;], keep=&quot;first&quot;)
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
    </tr>
    <tr>
      <td>1</td>
      <td>A002</td>
      <td>C002</td>
      <td>鈴木</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-02</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
    </tr>
    <tr>
      <td>5</td>
      <td>A005</td>
      <td>C004</td>
      <td>高橋</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-06</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>8</td>
      <td>A007</td>
      <td>C006</td>
      <td>山田</td>
      <td>マウス</td>
      <td>2500</td>
      <td>2026-04-08</td>
    </tr>
  </tbody>
</table>
</div>

<p>ただし、この記事では <code>drop_duplicates()</code> の詳しい削除パターンには深入りしません。<br />
詳しく学ぶ場合は、重複削除を扱う記事で確認するのがおすすめです。</p>
<p>大切なのは、次の順番です。</p>
<ol>
<li><code>duplicated()</code> で重複を確認する</li>
<li><code>keep=False</code> などで重複グループ全体を見る</li>
<li>削除してよいか判断する</li>
<li>必要な場合だけ <code>drop_duplicates()</code> を使う</li>
</ol>

<h2><span id="toc18">9. value_counts()やgroupby()との使い分け</span></h2>
<p>重複確認では、<code>value_counts()</code> や <code>groupby()</code> も使えます。</p>
<p>ただし、それぞれ得意なことが少し違います。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>方法</th>
  <th>得意なこと</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>duplicated()</code></td>
  <td>どの行が重複しているか確認する</td>
</tr>
<tr>
  <td><code>value_counts()</code></td>
  <td>列ごとの値が何回出ているか確認する</td>
</tr>
<tr>
  <td><code>groupby().size()</code></td>
  <td>グループごとの件数を確認する</td>
</tr>
<tr>
  <td><code>drop_duplicates()</code></td>
  <td>重複行を削除する</td>
</tr>
</tbody>
</table></div>
<p>たとえば、注文番号ごとの出現回数を見たいだけなら、<code>value_counts()</code> が便利です。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;注文番号&quot;].value_counts()
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>count</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A003</td>
      <td>2</td>
    </tr>
    <tr>
      <td>A006</td>
      <td>2</td>
    </tr>
    <tr>
      <td>A001</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A002</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A004</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A005</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A007</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
</div>

<p><code>groupby().size()</code> を使っても、注文番号ごとの件数を確認できます。</p>

<pre class="line-numbers"><code class="language-python">df.groupby(&quot;注文番号&quot;).size()
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A001</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A002</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A003</td>
      <td>2</td>
    </tr>
    <tr>
      <td>A004</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A005</td>
      <td>1</td>
    </tr>
    <tr>
      <td>A006</td>
      <td>2</td>
    </tr>
    <tr>
      <td>A007</td>
      <td>1</td>
    </tr>
  </tbody>
</table>
</div>

<p>ただし、<code>value_counts()</code> や <code>groupby().size()</code> は「何件あるか」を見るのに向いています。<br />
一方で、<code>duplicated()</code> は「どの行が重複として扱われるか」を見るのに向いています。</p>
<p>行そのものを確認したいときは、<code>duplicated()</code> を使うと分かりやすいです。</p>

<h2><span id="toc19">削除前チェックリスト：重複行を消す前に確認すること</span></h2>
<p><code>duplicated()</code> で重複が見つかっても、すぐに削除する必要はありません。</p>
<p>削除前には、次の表で確認すると安全です。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>確認すること</th>
  <th>見るポイント</th>
  <th>判断の例</th>
</tr>
</thead>
<tbody>
<tr>
  <td>行全体が完全に同じか</td>
  <td>すべての列が同じか</td>
  <td>完全一致なら二重登録の可能性が高い</td>
</tr>
<tr>
  <td>IDや注文番号だけが同じか</td>
  <td>商品・日付・金額が違わないか</td>
  <td>同じ顧客の別注文なら残す</td>
</tr>
<tr>
  <td>どの列を基準にするか</td>
  <td><code>subset</code> に指定する列</td>
  <td>注文番号、顧客ID、顧客ID＋注文番号など</td>
</tr>
<tr>
  <td>重複グループ全体を見たか</td>
  <td><code>keep=False</code> で確認したか</td>
  <td>最初の行も含めて確認できる</td>
</tr>
<tr>
  <td>削除後の影響はあるか</td>
  <td>集計や売上合計が変わるか</td>
  <td>集計前に確認しておく</td>
</tr>
</tbody>
</table></div>
<p>このチェックを入れることで、<code>drop_duplicates()</code> で必要なデータまで消してしまうリスクを減らせます。</p>

<h2><span id="toc20">11. よくあるミスと注意点</span></h2>
<p>ここでは、初心者がつまずきやすいポイントを整理します。</p>

<h3><span id="toc21">ミス1：duplicated()で重複が削除されると思ってしまう</span></h3>
<p><code>duplicated()</code> は重複を削除しません。<br />
<code>True</code> / <code>False</code> で確認するだけです。</p>

<pre class="line-numbers"><code class="language-python"># duplicated()は削除ではなく、True / False の確認です
df.duplicated()
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>False</td>
    </tr>
    <tr>
      <td>1</td>
      <td>False</td>
    </tr>
    <tr>
      <td>2</td>
      <td>False</td>
    </tr>
    <tr>
      <td>3</td>
      <td>True</td>
    </tr>
    <tr>
      <td>4</td>
      <td>False</td>
    </tr>
    <tr>
      <td>5</td>
      <td>False</td>
    </tr>
    <tr>
      <td>6</td>
      <td>False</td>
    </tr>
    <tr>
      <td>7</td>
      <td>True</td>
    </tr>
    <tr>
      <td>8</td>
      <td>False</td>
    </tr>
  </tbody>
</table>
</div>

<p>削除したい場合は <code>drop_duplicates()</code> を使います。<br />
ただし、削除する前に必ず中身を確認しましょう。</p>

<h3><span id="toc22">ミス2：Trueを「残す行」だと思ってしまう</span></h3>
<p><code>duplicated()</code> の <code>True</code> は、「重複と判定された行」という意味です。<br />
「残す行」という意味ではありません。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>結果</th>
  <th>意味</th>
</tr>
</thead>
<tbody>
<tr>
  <td><code>False</code></td>
  <td>最初に出てきた行、または重複していない行</td>
</tr>
<tr>
  <td><code>True</code></td>
  <td>重複と判定された行</td>
</tr>
</tbody>
</table></div>
<p>特に初期設定の <code>keep='first'</code> では、最初の行は <code>False</code> になります。</p>

<h3><span id="toc23">ミス3：名前だけで重複削除しようとする</span></h3>
<p>同じ名前があるからといって、同じ人とは限りません。<br />
また、同じ人でも別の商品を注文している可能性があります。</p>
<p>名前だけで確認すると、削除してはいけないデータまで重複に見えることがあります。</p>

<pre class="line-numbers"><code class="language-python">df[df.duplicated(subset=[&quot;氏名&quot;], keep=False)]
</code></pre>

<div class="colab-table-wrap">
<table class="wp-block-table">
  <thead>
    <tr>
      <th></th>
      <th>注文番号</th>
      <th>顧客ID</th>
      <th>氏名</th>
      <th>商品</th>
      <th>金額</th>
      <th>注文日</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>A001</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>ノートPC</td>
      <td>120000</td>
      <td>2026-04-01</td>
    </tr>
    <tr>
      <td>2</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>3</td>
      <td>A003</td>
      <td>C003</td>
      <td>田中</td>
      <td>キーボード</td>
      <td>8000</td>
      <td>2026-04-03</td>
    </tr>
    <tr>
      <td>4</td>
      <td>A004</td>
      <td>C001</td>
      <td>佐藤</td>
      <td>モニター</td>
      <td>30000</td>
      <td>2026-04-05</td>
    </tr>
    <tr>
      <td>6</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
    <tr>
      <td>7</td>
      <td>A006</td>
      <td>C005</td>
      <td>伊藤</td>
      <td>USBメモリ</td>
      <td>1500</td>
      <td>2026-04-07</td>
    </tr>
  </tbody>
</table>
</div>

<p>この例では、<code>佐藤</code> さんが2回出ています。<br />
しかし、注文番号と商品が違うため、単純に削除してよいとは言えません。</p>
<p>重複確認では、名前だけではなく、<code>顧客ID</code>、<code>注文番号</code>、<code>注文日</code> なども合わせて確認しましょう。</p>

<h3><span id="toc24">ミス4：subsetを指定せずに「重複がない」と判断してしまう</span></h3>
<p><code>subset</code> を指定しない場合、行全体が同じかどうかを見ます。</p>
<p>そのため、注文番号は同じでも、どこか1列だけ違うと、行全体としては重複にならないことがあります。</p>
<p>「注文番号だけを見たい」「顧客IDだけを見たい」という目的がある場合は、<code>subset</code> を使いましょう。</p>

<h3><span id="toc25">ミス5：重複は必ず悪いデータだと思ってしまう</span></h3>
<p>重複しているように見えるデータでも、実際には意味のあるデータの場合があります。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>重複して見える例</th>
  <th>削除してよいか</th>
</tr>
</thead>
<tbody>
<tr>
  <td>同じ顧客IDが複数回出る</td>
  <td>同じ顧客の複数注文なら残す</td>
</tr>
<tr>
  <td>同じ商品名が複数回出る</td>
  <td>商品別集計では普通にありえる</td>
</tr>
<tr>
  <td>同じ注文番号が完全に同じ内容で2回出る</td>
  <td>二重登録の可能性があるため確認する</td>
</tr>
<tr>
  <td>行全体が完全に同じ</td>
  <td>重複登録の可能性が高い</td>
</tr>
</tbody>
</table></div>
<p>重複確認の目的は、機械的に消すことではありません。<br />
「残すべきか、削除すべきか」を判断することです。</p>

<h2><span id="toc26">12. 前処理の流れの中でduplicated()を使うタイミング</span></h2>
<p><code>duplicated()</code> は、Pandasの前処理の中で早めに使うと便利です。</p>
<p>おすすめの流れは次のとおりです。</p>
<div class="colab-table-wrap"><table class="wp-block-table">
<thead>
<tr>
  <th>順番</th>
  <th>確認内容</th>
  <th>使うメソッド例</th>
</tr>
</thead>
<tbody>
<tr>
  <td>1</td>
  <td>データの先頭を見る</td>
  <td><code>head()</code></td>
</tr>
<tr>
  <td>2</td>
  <td>列名・型・欠損数を見る</td>
  <td><code>info()</code></td>
</tr>
<tr>
  <td>3</td>
  <td>統計量を見る</td>
  <td><code>describe()</code></td>
</tr>
<tr>
  <td>4</td>
  <td>欠損値を確認する</td>
  <td><code>isnull()</code></td>
</tr>
<tr>
  <td>5</td>
  <td>重複行を確認する</td>
  <td><code>duplicated()</code></td>
</tr>
<tr>
  <td>6</td>
  <td>必要に応じて重複を削除する</td>
  <td><code>drop_duplicates()</code></td>
</tr>
<tr>
  <td>7</td>
  <td>件数やグループごとに確認する</td>
  <td><code>value_counts()</code>、<code>groupby()</code></td>
</tr>
<tr>
  <td>8</td>
  <td>表形式に集計する</td>
  <td><code>pivot_table()</code></td>
</tr>
</tbody>
</table></div>
<p>重複確認をせずに集計へ進むと、件数や合計金額が二重に数えられることがあります。</p>
<p>そのため、集計や可視化の前に、<code>duplicated()</code> で重複の有無を確認しておくと安心です。</p>

<h2><span id="toc27">13. まとめ</span></h2>
<p>この記事では、Pandasの <code>duplicated()</code> を使って重複行を確認する方法を解説しました。</p>
<p>重要なポイントを整理します。</p>
<ul>
<li><code>duplicated()</code> は、重複行を <code>True</code> / <code>False</code> で確認するメソッド</li>
<li><code>duplicated()</code> は重複を削除しない</li>
<li>重複行だけを見たいときは <code>df[df.duplicated()]</code> を使う</li>
<li>重複件数を見たいときは <code>df.duplicated().sum()</code> を使う</li>
<li>特定列を基準にしたいときは <code>subset</code> を使う</li>
<li><code>keep='first'</code>、<code>keep='last'</code>、<code>keep=False</code> で重複判定のされ方が変わる</li>
<li>重複を削除したいときは、確認後に <code>drop_duplicates()</code> を使う</li>
<li>重複は必ずしも悪いデータではないため、削除前に中身を確認する</li>
</ul>
<p>初心者のうちは、次の順番で考えるのがおすすめです。</p>
<ol>
<li>まず <code>duplicated()</code> で重複を確認する</li>
<li><code>keep=False</code> で重複グループ全体を見る</li>
<li><code>subset</code> で重複の基準列を決める</li>
<li>削除してよいと判断できたら <code>drop_duplicates()</code> に進む</li>
</ol>
<p><code>duplicated()</code> を使えるようになると、データを削除する前に安全に確認できるようになります。</p>

<h2><span id="toc28">次に読みたい関連記事</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-isnull/">欠損値を可視化して攻略！Pandas isnullとヒートマップ活用術</a><br />
重複確認とあわせて、欠損値も確認したいときにおすすめです。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-drop/">Pandas dropna()・drop_duplicates()の使い方｜欠損/重複の削除とdrop()基本</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-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 />
重複データがあるときに、pivotとpivot_tableをどう使い分けるかを学べます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-reset-index/">pandas reset_index()の使い方｜インデックスを振り直す・drop=Trueを初心者向けに解説</a><br />
重複削除後にインデックスを整えたいときに役立ちます。</p>
</li>
<li><p><a href="https://pythondatalab.com/pandas-concat/">Pandas concat完全ガイド｜複数CSVからDataFrameを縦横結合する方法</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="toc29"> カテゴリから探す</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-1777878155999" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc30">pandas duplicated()は何をするメソッドですか？</span></h3>
<div class="rank-math-answer ">

<p><code>duplicated()</code> は、DataFrameの行が重複しているかどうかを <code>True</code> / <code>False</code> で確認するメソッドです。<br />重複を削除するのではなく、削除前にどの行が重複と判定されるかを確認するために使います。</p>

</div>
</div>
<div id="faq-question-1777878183839" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">duplicated()とdrop_duplicates()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>duplicated()</code> は重複行を <code>True</code> / <code>False</code> で確認します。<br /><code>drop_duplicates()</code> は重複行を削除したDataFrameを返します。<br />削除前の確認には <code>duplicated()</code>、削除には <code>drop_duplicates()</code> と考えると分かりやすいです。</p>

</div>
</div>
<div id="faq-question-1777878200562" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">重複行だけを表示するにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>次のように書きます。<br /><code>df[df.duplicated()]</code></p>
<p>特定の列を基準にしたい場合は、次のように <code>subset</code> を指定します。<br /><code>df[df.duplicated(subset=["注文番号"], keep=False)]</code></p>
<p><code>keep=False</code> を使うと、重複しているグループ全体を確認しやすくなります。</p>

</div>
</div>
<div id="faq-question-1777878223629" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">duplicated().sum()は何を数えていますか？</span></h3>
<div class="rank-math-answer ">

<p><code>keep=False</code> を使うと、重複しているグループ全体を確認しやすくなります。</p>

</div>
</div>
<div id="faq-question-1777878240571" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">duplicated().sum()は何を数えていますか？</span></h3>
<div class="rank-math-answer ">

<p><code>duplicated()</code> で <code>True</code> になった行数を数えています。<br />つまり、重複と判定された行が何件あるかを確認できます。<br />ただし、この件数は「削除すべき件数」とは限りません。削除前に、実際の行の中身を確認しましょう。</p>

</div>
</div>
<div id="faq-question-1777878253901" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">subsetは何のために使いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>subset</code> は、重複判定に使う列を指定するための引数です。<br />たとえば、注文番号だけを基準にしたい場合は次のように書きます。<br /><code>df.duplicated(subset=["注文番号"])</code></p>
<p>行全体ではなく、特定列だけを基準に重複確認したいときに使います。</p>

</div>
</div>
<div id="faq-question-1777878271845" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc36">keep=&#8217;first&#8217;、keep=&#8217;last&#8217;、keep=Falseの違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>keep='first'</code> は最初の行を残す扱いにし、2回目以降を <code>True</code> にします。<br /><code>keep='last'</code> は最後の行を残す扱いにし、それより前を <code>True</code> にします。<br /><code>keep=False</code> は、重複している行をすべて <code>True</code> にします。<br />重複グループ全体を確認したいときは、<code>keep=False</code> が便利です。</p>

</div>
</div>
<div id="faq-question-1777878288549" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc37">重複行は必ず削除したほうがよいですか？</span></h3>
<div class="rank-math-answer ">

<p>必ず削除する必要はありません。<br />同じ顧客が複数回注文している場合や、同じ商品が複数回売れている場合は、意味のあるデータです。<br />削除する前に、何を基準に重複と見るのかを確認しましょう。</p>

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

<p><code>value_counts()</code> は、値が何回出ているかを確認するのに向いています。<br /><code>duplicated()</code> は、どの行が重複として判定されるかを確認するのに向いています。<br />件数を見たいときは <code>value_counts()</code>、行を確認したいときは <code>duplicated()</code> と考えると分かりやすいです。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-duplicated/">pandas duplicated()の使い方｜重複行の確認・subset・keepを初心者向けに解説</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-duplicated/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas map()の使い方｜辞書で値を変換・新しい列を作る方法を初心者向けに解説</title>
		<link>https://pythondatalab.com/pandas-map/</link>
					<comments>https://pythondatalab.com/pandas-map/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Sat, 02 May 2026 10:16:54 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=2009</guid>

					<description><![CDATA[<p>pandasのmap()を使って、辞書で値を変換する方法を初心者向けに解説。数値コードや文字列コードをラベルに変換する例、新しい列を作る方法、辞書にない値がNaNになる原因、replace()・astype()・merge()との違いまで整理します。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-map/">pandas 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[

<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;
    white-space: pre;
    overflow-x: auto;
  }
  .colab-article .colab-output {
    margin: 0 !important;
    padding: 0.75em 1em;
    background: #f7f7f7;
    border: 1px solid #e5e5e5;
    overflow-x: auto;
    white-space: pre;
  }
  .colab-article .colab-output-text {
    margin: 0.6em 0 0.2em;
    font-weight: 600;
  }
  .colab-article .colab-table-wrap {
    max-width: 100%;
    overflow-x: auto;
    margin: 0.6em 0 1em;
  }
  .colab-article table.wp-block-table {
    width: auto;
    border-collapse: collapse;
  }
  .colab-article table.wp-block-table th,
  .colab-article table.wp-block-table td {
    border: 1px solid #ddd;
  }
  .colab-article .colab-figure {
    margin: 1em 0;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>



<p>CSVを読み込んだあと、列の値が <code>1</code>、<code>2</code>、<code>A</code>、<code>B</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;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</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;">A</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;">B</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;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">対応表にまだ登録していないコード</td>
</tr>
</tbody>
</table></div>
<p>このまま <code>value_counts()</code> や <code>groupby()</code> で集計することもできますが、結果が <code>1</code> や <code>A</code> のままだと読み取りにくくなります。</p>
<p>そこで使いやすいのが、Pandasの <code>map()</code> です。<br/>
<code>map()</code> は、<strong>1列の値を、辞書などの対応表に従って別の値へ変換したいとき</strong>に使います。</p>
<p>この記事では、<code>pandas map()の使い方</code>を、辞書で値を変換する基本から、新しい列を作る方法、辞書にない値が <code>NaN</code> になる注意点まで、初心者向けに整理します。</p>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-9" checked><label class="toc-title" for="toc-checkbox-9">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">まず結論：map()は「対応表で1列を変換する」ときに使う</a></li><li><a href="#toc2" tabindex="0">この記事でわかること</a></li><li><a href="#toc3" tabindex="0">Pandas DataFrame入門シリーズでの位置づけ</a></li><li><a href="#toc4" tabindex="0">map()はどんな場面で使うのか</a></li><li><a href="#toc5" tabindex="0">map()と似た機能の使い分け</a></li><li><a href="#toc6" tabindex="0">サンプルデータを作成する</a></li><li><a href="#toc7" tabindex="0">変換前に値の種類を確認する</a></li><li><a href="#toc8" tabindex="0">辞書を使って数値コードをラベルに変換する</a></li><li><a href="#toc9" tabindex="0">map()で新しい列を作る</a></li><li><a href="#toc10" tabindex="0">辞書にない値がNaNになる例</a></li><li><a href="#toc11" tabindex="0">fillna()で未対応コードを補う</a></li><li><a href="#toc12" tabindex="0">文字列のコードをカテゴリ名に変換する</a></li><li><a href="#toc13" tabindex="0">map()とreplace()の違い</a></li><li><a href="#toc14" tabindex="0">map()とastype()・merge()・apply()の違い</a><ol><li><a href="#toc15" tabindex="0">map()とastype()の違い</a></li><li><a href="#toc16" tabindex="0">map()とmerge()の違い</a></li><li><a href="#toc17" tabindex="0">map()とapply()の違い</a></li></ol></li><li><a href="#toc18" tabindex="0">文字列の「1」と数値の1は別物として扱われる</a></li><li><a href="#toc19" tabindex="0">map()後に集計へ進む</a></li><li><a href="#toc20" tabindex="0">よくあるつまずきと確認ポイント</a></li><li><a href="#toc21" tabindex="0">まとめ</a></li><li><a href="#toc22" tabindex="0">次に読みたい関連記事</a><ol><li><a href="#toc23" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc24" tabindex="0">pandasのmap()は何をするメソッドですか？</a></li><li><a href="#toc25" tabindex="0">map()とreplace()は何が違いますか？</a></li><li><a href="#toc26" tabindex="0">map()で辞書にない値がNaNになるのはなぜですか？</a></li><li><a href="#toc27" tabindex="0">map()で新しい列を作るにはどうすればよいですか？</a></li><li><a href="#toc28" tabindex="0">数値の1と文字列の&#8221;1&#8243;でmap()の結果は変わりますか？</a></li><li><a href="#toc29" tabindex="0">map()とastype()は何が違いますか？</a></li><li><a href="#toc30" tabindex="0">map()とmerge()はどう使い分けますか？</a></li><li><a href="#toc31" tabindex="0">map()したあとに結果を確認するにはどうすればよいですか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">まず結論：map()は「対応表で1列を変換する」ときに使う</span></h2>
<blockquote>
<p><strong>結論</strong><br/>
pandasの <code>map()</code> は、DataFrameの1列に入っている値を、辞書などの対応表に従って別の値へ変換したいときに使います。<br/>
たとえば、<code>1</code> を <code>男性</code>、<code>2</code> を <code>女性</code>、<code>A</code> を <code>通常会員</code> のように、コード値を人が読めるラベルへ変換するときに便利です。</p>
</blockquote>
<p>この記事では、まず辞書を使った基本形に絞って説明します。<br/>
難しい関数処理や速度比較には深入りせず、CSVを読み込んだあとに実際によく使う前処理として、<code>map()</code> の使いどころを整理します。</p>

<h2><span id="toc2">この記事でわかること</span></h2>
<ul>
<li><code>map()</code> がどんな場面で役立つか</li>
<li>辞書を使って値を変換する基本</li>
<li>数値コードや文字列コードをラベルに変換する方法</li>
<li><code>map()</code> で新しい列を作る方法</li>
<li>辞書にない値が <code>NaN</code> になる理由と確認方法</li>
<li><code>map()</code> と <code>replace()</code>、<code>astype()</code>、<code>merge()</code> の違い</li>
<li>集計前の前処理として <code>map()</code> を使う流れ</li>
</ul>

<h2><span id="toc3">Pandas DataFrame入門シリーズでの位置づけ</span></h2>
<p><code>map()</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;">流れ</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>read_csv()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">CSVをDataFrameとして読み込む</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>head()</code> / <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;">値の確認</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>map()</code> / <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>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;">型変換</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>groupby()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">整えた列を使って集計する</td>
</tr>
</tbody>
</table></div>
<p>DataFrameの基本から確認したい場合は、<a href="https://pythondatalab.com/pandas-dataframe/">Pandas DataFrame入門</a> もあわせて確認すると流れがつかみやすくなります。</p>

<h2><span id="toc4">map()はどんな場面で使うのか</span></h2>
<p>結論からいうと、<code>map()</code> は <strong>1列の値を、対応表に従って別の値へ変換したいとき</strong>に使います。</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;">変換前</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>1</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>2</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>A</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>B</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>C</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>VIP</code></td>
</tr>
</tbody>
</table></div>
<p><code>map()</code> は、特に次のような場面で便利です。</p>
<ul>
<li>数値コードをわかりやすいラベルに変換したい</li>
<li><code>A</code>、<code>B</code>、<code>C</code> のようなランクコードを名前に変えたい</li>
<li>既存列をもとに、新しい説明用の列を作りたい</li>
<li><code>groupby()</code> やグラフ化の前に、集計結果を読みやすくしたい</li>
</ul>
<p>ここで大事なのは、<code>map()</code> は基本的に <strong>DataFrame全体ではなく、1列、つまりSeriesに使う</strong>という点です。</p>

<h2><span id="toc5">map()と似た機能の使い分け</span></h2>
<p>Pandasには、値を変える処理がいくつかあります。<br/>
ここで先に整理しておくと、<code>map()</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;">やりたいこと</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;">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;"><code>1 → 男性</code>、<code>A → 通常会員</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;"><code>Tokyo</code> と <code>tokyo</code> を <code>東京</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>fillna()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>NaN → 未分類</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;">文字列の <code>"100"</code> を数値の <code>100</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;">別DataFrameの対応表と結合したい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>merge()</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;">複雑な条件や関数を使いたい</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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">単純な対応表では足りないとき</td>
</tr>
</tbody>
</table></div>
<p>この記事では、まず初心者が使いやすい <strong>辞書を使った <code>map()</code></strong> に絞って説明します。</p>
<p>表記ゆれの置換を詳しく知りたい場合は、<a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方</a> を参考にしてください。<br/>
型変換を確認したい場合は、<a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方</a> が近い内容です。</p>

<h2><span id="toc6">サンプルデータを作成する</span></h2>
<p>ここでは、会員データを例にします。</p>
<p><code>gender_code</code> には性別コード、<code>member_rank</code> には会員ランクのコードが入っているとします。<br/>
また、あえて対応表にない値も入れて、<code>map()</code> でよくあるつまずきを確認できるようにします。</p>

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

data = {
    &quot;customer_id&quot;: [101, 102, 103, 104, 105, 106],
    &quot;gender_code&quot;: [1, 2, 1, 3, 2, 1],
    &quot;member_rank&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;A&quot;, &quot;D&quot;, &quot;B&quot;],
    &quot;purchase_amount&quot;: [1200, 3500, 5800, 900, 1500, 4200]
}

df = pd.DataFrame(data)
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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">customer_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">purchase_amount</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</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;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3500</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</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;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4200</td>
</tr>
</tbody>
</table></div>

<p>このデータでは、<code>gender_code</code> の <code>1</code> や <code>2</code>、<code>member_rank</code> の <code>A</code> や <code>B</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;">列名</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>gender_code</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>1</code>、<code>2</code>、<code>3</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>member_rank</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>A</code>、<code>B</code>、<code>C</code>、<code>D</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>通常会員</code>、<code>優良会員</code>、<code>VIP</code>、未分類など</td>
</tr>
</tbody>
</table></div>
<p>このようなときに、<code>map()</code> で対応表を使って変換します。</p>

<h2><span id="toc7">変換前に値の種類を確認する</span></h2>
<p><code>map()</code> を使う前に、まずどんな値が入っているかを確認しておくと安全です。</p>
<p>特に、辞書にない値があると <code>NaN</code> になることがあるため、変換前に <code>value_counts()</code> で確認しておくと失敗に気づきやすくなります。</p>

<pre class="line-numbers"><code class="language-python">print(&quot;gender_code の値の種類&quot;)
display(df[&quot;gender_code&quot;].value_counts(dropna=False))

print(&quot;member_rank の値の種類&quot;)
display(df[&quot;member_rank&quot;].value_counts(dropna=False))</code></pre>

<p class="colab-output-text">gender_code の値の種類</p>

<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;"></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;">1</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;">2</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;">1</td>
</tr>
</tbody>
</table></div>

<p class="colab-output-text">member_rank の値の種類</p>

<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;"></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;">A</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;">B</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;">C</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;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table></div>

<p>ここで、<code>gender_code</code> には <code>1</code>、<code>2</code>、<code>3</code> があり、<code>member_rank</code> には <code>A</code>、<code>B</code>、<code>C</code>、<code>D</code> があることがわかります。</p>
<p>この確認をせずに変換すると、「辞書に入れ忘れた値」があとから <code>NaN</code> として出てきて、原因がわかりにくくなることがあります。</p>
<p><code>value_counts()</code> の基本は、<a href="https://pythondatalab.com/pandas-value-counts/">pandas value_counts()の使い方</a> でも詳しく解説しています。</p>

<h2><span id="toc8">辞書を使って数値コードをラベルに変換する</span></h2>
<p>まずは、<code>gender_code</code> の <code>1</code> と <code>2</code> を、それぞれ <code>男性</code>、<code>女性</code> に変換します。</p>
<p><code>map()</code> では、次のように「変換前の値」と「変換後の値」を辞書で用意します。</p>

<pre class="line-numbers"><code class="language-python">gender_map = {
    1: &quot;男性&quot;,
    2: &quot;女性&quot;
}

df[&quot;gender_code&quot;].map(gender_map)</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</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;">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>
</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>
</tr>
</tbody>
</table></div>

<p>結果を見ると、<code>1</code> は <code>男性</code>、<code>2</code> は <code>女性</code> に変換されています。</p>
<p>一方で、<code>3</code> は辞書に含まれていないため、<code>NaN</code> になっています。<br/>
ここが <code>map()</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;">元の値</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">辞書にあるか</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>map()</code>後の値</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>1</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">ある</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>2</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">ある</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>3</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">ない</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>NaN</code></td>
</tr>
</tbody>
</table></div>
<p><code>NaN</code> は必ずしもエラーではありません。<br/>
「対応表にない値があった」というサインとして確認することが大切です。</p>

<h2><span id="toc9">map()で新しい列を作る</span></h2>
<p>初心者のうちは、元の列をいきなり上書きするより、<strong>新しい列として追加する</strong>ほうが安全です。</p>
<p>たとえば、<code>gender_code</code> はそのまま残し、変換後の値を <code>gender_label</code> という新しい列に入れます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;gender_label&quot;] = df[&quot;gender_code&quot;].map(gender_map)
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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">customer_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">purchase_amount</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_label</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</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;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3500</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;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</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;">104</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</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;">105</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</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;">106</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">男性</td>
</tr>
</tbody>
</table></div>

<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;">方法</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;">残らない</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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">変換前後を比べやすい</td>
</tr>
</tbody>
</table></div>
<p>上書き自体が悪いわけではありません。<br/>
ただし、最初は <code>gender_label</code> のような新しい列を作るほうが、ミスに気づきやすくなります。</p>
<p>新しい列の作り方を広く確認したい場合は、<a href="https://pythondatalab.com/pandas-add-column/">pandasで新しい列を追加する方法</a> も参考になります。</p>

<h2><span id="toc10">辞書にない値がNaNになる例</span></h2>
<p><code>map()</code> では、辞書にない値は元の値のまま残るのではなく、<code>NaN</code> になることがあります。</p>
<p>この性質は便利でもあります。<br/>
なぜなら、「対応表に入っていない値がある」と気づけるからです。</p>

<pre class="line-numbers"><code class="language-python">print(&quot;gender_label の欠損数&quot;)
display(df[&quot;gender_label&quot;].isnull().sum())

print(&quot;gender_label の値の種類&quot;)
display(df[&quot;gender_label&quot;].value_counts(dropna=False))</code></pre>

<p class="colab-output-text">gender_label の欠損数</p>

<pre class="colab-output">np.int64(1)</pre>

<p class="colab-output-text">gender_label の値の種類</p>

<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;"></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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table></div>

<p>この結果から、<code>gender_label</code> に <code>NaN</code> があることが確認できます。</p>
<p>今回のサンプルでは、<code>gender_code</code> の <code>3</code> を辞書に入れていないため、<code>NaN</code> になっています。<br/>
つまり、<code>3</code> は「欠損値そのもの」ではなく、<strong>対応表にまだ登録していないコード</strong>として扱います。</p>
<p>このように、<code>map()</code> 後は次の確認をすると安心です。</p>
<ul>
<li><code>isnull().sum()</code> で <code>NaN</code> の数を確認する</li>
<li><code>value_counts(dropna=False)</code> で変換後の値を確認する</li>
<li>必要に応じて、辞書に値を追加するか、<code>fillna()</code> で補う</li>
</ul>
<p>欠損値の確認や考え方は、<a href="https://pythondatalab.com/pandas-info-describe/">Pandas info()とdescribe()の違い</a> や <a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方</a> ともつながります。</p>

<h2><span id="toc11">fillna()で未対応コードを補う</span></h2>
<p>辞書にない値を <code>NaN</code> のままにしたくない場合は、<code>fillna()</code> で補う方法があります。</p>
<p>今回は、<code>gender_code</code> の <code>3</code> を「未対応」として表示します。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;gender_label&quot;] = df[&quot;gender_code&quot;].map(gender_map).fillna(&quot;未対応&quot;)
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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">customer_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">purchase_amount</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_label</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</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;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3500</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;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</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;">104</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</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;">105</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</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;">106</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4200</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">男性</td>
</tr>
</tbody>
</table></div>

<p><code>fillna("未対応")</code> を使うことで、辞書にない値をわかりやすく表示できました。</p>
<p>ただし、すべての <code>NaN</code> を機械的に「未対応」にしてよいとは限りません。<br/>
本当に未対応コードなのか、入力ミスなのか、欠損値なのかは、データの意味を確認して判断する必要があります。</p>

<h2><span id="toc12">文字列のコードをカテゴリ名に変換する</span></h2>
<p>次に、<code>member_rank</code> の <code>A</code>、<code>B</code>、<code>C</code> を会員ランク名に変換します。</p>
<p>ここでも、元の <code>member_rank</code> を残し、変換後の値を <code>rank_label</code> という新しい列にします。</p>

<pre class="line-numbers"><code class="language-python">rank_map = {
    &quot;A&quot;: &quot;通常会員&quot;,
    &quot;B&quot;: &quot;優良会員&quot;,
    &quot;C&quot;: &quot;VIP&quot;
}

df[&quot;rank_label&quot;] = df[&quot;member_rank&quot;].map(rank_map)
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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">customer_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">purchase_amount</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_label</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">rank_label</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</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;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3500</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;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">男性</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">VIP</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</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;">105</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">女性</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;">106</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4200</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>A</code>、<code>B</code>、<code>C</code> は変換できましたが、<code>D</code> は辞書にないため <code>NaN</code> になっています。</p>
<p>ここでも、変換前後を確認しておきます。</p>

<pre class="line-numbers"><code class="language-python">print(&quot;rank_label の値の種類&quot;)
display(df[&quot;rank_label&quot;].value_counts(dropna=False))

print(&quot;rank_label の欠損数&quot;)
display(df[&quot;rank_label&quot;].isnull().sum())</code></pre>

<p class="colab-output-text">rank_label の値の種類</p>

<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;"></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;">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;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">VIP</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
</tr>
</tbody>
</table></div>

<p class="colab-output-text">rank_label の欠損数</p>

<pre class="colab-output">np.int64(1)</pre>

<p><code>D</code> を未分類として扱うなら、<code>fillna("未分類")</code> のように補うことができます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;rank_label&quot;] = df[&quot;member_rank&quot;].map(rank_map).fillna(&quot;未分類&quot;)
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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">customer_id</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">member_rank</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">purchase_amount</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_label</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">rank_label</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1200</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;">102</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3500</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;">103</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">C</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">男性</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">VIP</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">A</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">900</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;">105</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">D</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</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;">106</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">B</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4200</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>
<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;">変換前の列</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>gender_code</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>gender_label</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>member_rank</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>rank_label</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">会員ランクコードをラベルに変換</td>
</tr>
</tbody>
</table></div>
<p>このように、<code>map()</code> は「コードの意味を人が読める形にする」前処理で役立ちます。</p>

<h2><span id="toc13">map()とreplace()の違い</span></h2>
<p><strong>迷ったら、コード値をラベルに変えるなら <code>map()</code>、表記ゆれを直すなら <code>replace()</code> と考えるとわかりやすいです。</strong></p>
<p><code>map()</code> と <code>replace()</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;">比較</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>map()</code></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>replace()</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;">対応表に従って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;">辞書にない値</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>NaN</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>1 → 男性</code>、<code>A → 通常会員</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>tokyo → 東京</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;">コード値をラベルにしたいならこちら</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">表記ゆれを直したいならこちら</td>
</tr>
</tbody>
</table></div>
<p>違いを確認するために、簡単な例を見てみます。</p>

<pre class="line-numbers"><code class="language-python">s = pd.Series([1, 2, 3])

mapping = {
    1: &quot;男性&quot;,
    2: &quot;女性&quot;
}

print(&quot;map() の結果&quot;)
display(s.map(mapping))

print(&quot;replace() の結果&quot;)
display(s.replace(mapping))</code></pre>

<p class="colab-output-text">map() の結果</p>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">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>
</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;">NaN</td>
</tr>
</tbody>
</table></div>

<p class="colab-output-text">replace() の結果</p>

<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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">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>
</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;">3</td>
</tr>
</tbody>
</table></div>

<p>この例では、<code>3</code> が辞書にありません。</p>
<ul>
<li><code>map()</code> では、<code>3</code> が <code>NaN</code> になります</li>
<li><code>replace()</code> では、<code>3</code> がそのまま残ります</li>
</ul>
<p>そのため、<strong>対応表にない値を見つけたい場合は <code>map()</code> が気づきやすい</strong>ことがあります。<br/>
一方で、表記ゆれを一部だけ直したい場合は <code>replace()</code> のほうが自然なこともあります。</p>
<p><code>replace()</code> の詳しい使い方は、<a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方</a> で確認できます。</p>

<h2><span id="toc14">map()とastype()・merge()・apply()の違い</span></h2>
<p><code>map()</code> と似て見える処理も、目的が違います。</p>
<h3><span id="toc15">map()とastype()の違い</span></h3>
<p><code>astype()</code> は、値の意味を変えるのではなく、データ型を変えるためのメソッドです。</p>
<p>たとえば、文字列の <code>"100"</code> を数値の <code>100</code> に変えるような場面では <code>astype()</code> を使います。<br/>
一方、<code>1</code> を <code>男性</code> に変えるように、値の意味をラベルへ変えるなら <code>map()</code> が向いています。</p>
<h3><span id="toc16">map()とmerge()の違い</span></h3>
<p>小さな対応表を辞書で持てるなら、<code>map()</code> がシンプルです。</p>
<p>一方で、商品マスタ、店舗マスタ、顧客マスタのように、対応表が別のDataFrameとしてある場合は <code>merge()</code> が向いています。<br/>
本格的な表結合を学ぶ場合は、<a href="https://pythondatalab.com/pandas-merge/">pandas mergeの使い方</a> が近い内容です。</p>
<h3><span id="toc17">map()とapply()の違い</span></h3>
<p>単純な対応変換なら、まずは <code>map()</code> で十分なことが多いです。</p>
<p><code>apply()</code> は、複雑な関数を使いたいときに便利ですが、この記事では深入りしません。<br/>
初心者のうちは、まず「辞書で対応変換するなら <code>map()</code>」と覚えると迷いにくくなります。</p>

<h2><span id="toc18">文字列の「1」と数値の1は別物として扱われる</span></h2>
<p><code>map()</code> では、辞書のキーと列の値が一致している必要があります。</p>
<p>たとえば、列の値が文字列の <code>"1"</code> なのに、辞書のキーが数値の <code>1</code> だと、うまく変換されないことがあります。</p>

<pre class="line-numbers"><code class="language-python">df_type = pd.DataFrame({
    &quot;gender_code&quot;: [&quot;1&quot;, &quot;2&quot;, &quot;1&quot;, &quot;3&quot;]
})

gender_map_number_key = {
    1: &quot;男性&quot;,
    2: &quot;女性&quot;
}

df_type[&quot;label_ng&quot;] = df_type[&quot;gender_code&quot;].map(gender_map_number_key)
df_type</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">label_ng</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;">1</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;">2</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;">1</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
</tbody>
</table></div>

<p><code>gender_code</code> は見た目は <code>1</code> や <code>2</code> ですが、実際には文字列です。<br/>
そのため、数値の <code>1</code>、<code>2</code> をキーにした辞書では対応できず、<code>NaN</code> になります。</p>
<p>この場合は、辞書のキーを文字列にそろえるか、列の型を変換します。</p>

<pre class="line-numbers"><code class="language-python">gender_map_string_key = {
    &quot;1&quot;: &quot;男性&quot;,
    &quot;2&quot;: &quot;女性&quot;
}

df_type[&quot;label_ok&quot;] = df_type[&quot;gender_code&quot;].map(gender_map_string_key).fillna(&quot;未対応&quot;)
df_type</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">gender_code</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">label_ng</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">label_ok</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;">1</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</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;">1</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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">3</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>
</tbody>
</table></div>

<p>このように、<code>map()</code> でうまく変換できないときは、次の点を確認しましょう。</p>
<ul>
<li>列の値が数値なのか文字列なのか</li>
<li>辞書のキーと列の値の型が合っているか</li>
<li>辞書にない値が含まれていないか</li>
<li>変換後に <code>NaN</code> が増えていないか</li>
</ul>
<p>型の確認や変換は、<a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方</a> とつながります。</p>

<h2><span id="toc19">map()後に集計へ進む</span></h2>
<p><code>map()</code> は、変換して終わりではありません。<br/>
読みやすいラベルに整えたあと、<code>groupby()</code> や可視化につなげると、分析結果がわかりやすくなります。</p>
<p>たとえば、会員ランク別に購入金額を集計してみます。</p>

<pre class="line-numbers"><code class="language-python">rank_summary = (
    df.groupby(&quot;rank_label&quot;, as_index=False)[&quot;purchase_amount&quot;]
      .sum()
      .rename(columns={&quot;purchase_amount&quot;: &quot;total_purchase_amount&quot;})
)

rank_summary</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;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">rank_label</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">total_purchase_amount</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;">VIP</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5800</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;">7700</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;">1500</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;">2100</td>
</tr>
</tbody>
</table></div>

<p><code>member_rank</code> の <code>A</code>、<code>B</code>、<code>C</code>、<code>D</code> のまま集計するより、<code>通常会員</code>、<code>優良会員</code>、<code>VIP</code>、<code>未分類</code> のように表示されたほうが、結果を読み取りやすくなります。</p>
<p>このように、<code>map()</code> は次の流れの中で役立ちます。</p>
<ol>
<li>CSVを読み込む</li>
<li><code>head()</code> や <code>info()</code> で確認する</li>
<li><code>value_counts()</code> で値の種類を見る</li>
<li><code>map()</code> でコード値をラベルに変換する</li>
<li>必要に応じて <code>fillna()</code> や <code>astype()</code> で整える</li>
<li><code>groupby()</code> やグラフで集計・可視化する</li>
</ol>
<p>集計の基本は <a href="https://pythondatalab.com/pandas-groupby-agg/">Pandas groupby×aggの使い方</a> に進むと理解しやすくなります。<br/>
グラフ化まで進めたい場合は、<a href="https://pythondatalab.com/matplotlib-bar-barh-stacked/">Matplotlib 棒グラフ入門</a> も関連します。</p>

<h2><span id="toc20">よくあるつまずきと確認ポイント</span></h2>
<p><code>map()</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;">つまずき</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>NaN</code>が出る</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(dropna=False)</code></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;">値の型と辞書のキーの型が違う</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>info()</code> や <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;">既存列を上書きしている</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>map()</code>より<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>map()</code>より<code>merge()</code>が向く場合がある</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">対応表がDataFrameか確認する</td>
</tr>
</tbody>
</table></div>
<p>特に大切なのは、<strong>変換前と変換後の確認</strong>です。<br/>
<code>map()</code> のコードだけを見るのではなく、変換前後の表を見比べるとミスに気づきやすくなります。</p>

<h2><span id="toc21">まとめ</span></h2>
<p>この記事では、<code>pandas map()</code> の使い方を、辞書で値を変換する前処理として解説しました。</p>
<p>重要なポイントは、次のとおりです。</p>
<ul>
<li><code>map()</code> は、1列の値を対応表に従って変換するときに使う</li>
<li>数値コードや文字列コードを、読みやすいラベルへ変換できる</li>
<li>初心者のうちは、元の列を上書きせず、新しい列として追加すると安全</li>
<li>辞書にない値は <code>NaN</code> になりやすい</li>
<li><code>NaN</code> が出たら、エラーと決めつけず、対応表にない値があるサインとして確認する</li>
<li><code>map()</code> 前後では、<code>value_counts()</code> や <code>isnull().sum()</code> で確認するとよい</li>
<li>表記ゆれ修正は <code>replace()</code>、型変換は <code>astype()</code>、別表との結合は <code>merge()</code> と使い分ける</li>
<li><code>map()</code> で値を整えると、<code>groupby()</code> やグラフ化の結果が読みやすくなる</li>
</ul>
<p><code>map()</code> は派手な機能ではありませんが、CSVを読み込んだあとに「コード値を人が読める形に整える」ための大切な前処理です。<br/>
まずは、<strong>対応表で1列を変換する</strong>、<strong>コード値を辞書でラベルに変換する</strong>という使い方から覚えておくと、DataFrameの集計や可視化へ進みやすくなります。</p>

<h2><span id="toc22">次に読みたい関連記事</span></h2>
<p>この記事の内容は、次の記事とつながっています。</p>
<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 読み込み＆保存入門</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-value-counts/">pandas value_counts()の使い方｜件数集計・割合表示・欠損値の数え方を解説</a></li>
<li><a href="https://pythondatalab.com/pandas-replace/">pandas replace()の使い方｜値の置換・表記ゆれ・欠損値変換を解説</a></li>
<li><a href="https://pythondatalab.com/pandas-add-column/">pandasで新しい列を追加する方法｜df[&#8216;列名&#8217;]・assign・条件付き列追加を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-fillna/">pandas fillna()の使い方｜欠損値を0・平均値・中央値・最頻値で埋める方法を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-astype/">pandas astype()の使い方｜文字列・数値への型変換とエラー対処を初心者向けに解説</a></li>
<li><a href="https://pythondatalab.com/pandas-merge/">pandas mergeの使い方｜DataFrame結合の違いと実例</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>
</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="toc23"> カテゴリから探す</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>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-1777716639177" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc24">pandasのmap()は何をするメソッドですか？</span></h3>
<div class="rank-math-answer ">

<p><code>map()</code> は、Series、つまりDataFrameの1列の値を、辞書や関数などに従って別の値へ変換するメソッドです。<br />初心者向けには、まず「1列のコード値を対応表でラベルに変換する方法」と考えるとわかりやすいです。</p>

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

<p><code>map()</code> は、対応表に従って1列を変換したいときに向いています。<br /><code>replace()</code> は、表記ゆれや特定の値を置換したいときに向いています。<br />たとえば、<code>1 → 男性</code>、<code>2 → 女性</code> のようなコード変換なら <code>map()</code> が自然です。<br />一方、<code>tokyo</code>、<code>Tokyo</code>、<code>TOKYO</code> を <code>東京</code> にそろえるような表記ゆれ修正なら <code>replace()</code> が向いています。</p>

</div>
</div>
<div id="faq-question-1777716699793" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc26">map()で辞書にない値がNaNになるのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p><code>map()</code> は、辞書にあるキーを使って値を変換します。<br />そのため、辞書にない値は対応先が見つからず、<code>NaN</code> になることがあります。<br />これはエラーとは限らず、「対応表に登録していない値がある」というサインです。<br /><code>value_counts(dropna=False)</code> や <code>isnull().sum()</code> で確認しましょう。</p>

</div>
</div>
<div id="faq-question-1777716719420" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc27">map()で新しい列を作るにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>次のように、変換結果を新しい列に代入します。<br /><code>df["gender_label"] = df["gender_code"].map(gender_map)</code><br />初心者のうちは、元の列を上書きするより、新しい列を作って変換前後を確認する方法がおすすめです。</p>

</div>
</div>
<div id="faq-question-1777716742272" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc28">数値の1と文字列の&#8221;1&#8243;でmap()の結果は変わりますか？</span></h3>
<div class="rank-math-answer ">

<p>変わることがあります。<br /><code>map()</code> では、列の値と辞書のキーが一致している必要があります。<br />列の値が文字列の <code>"1"</code> なら、辞書のキーも <code>"1"</code> にする必要があります。<br />数値の <code>1</code> をキーにした辞書では対応できず、<code>NaN</code> になることがあります。</p>

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

<p><code>map()</code> は、値の意味を別の値へ変換するために使います。<br /><code>astype()</code> は、データ型を変えるために使います。<br />たとえば、<code>1 → 男性</code> は <code>map()</code>、<code>"100" → 100</code> のような型変換は <code>astype()</code> と考えるとわかりやすいです。</p>

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

<p>小さな対応表を辞書で書けるなら、<code>map()</code> がシンプルです。<br />一方、対応表が別のDataFrameとしてある場合や、複数列をもとに結合したい場合は <code>merge()</code> が向いています。</p>

</div>
</div>
<div id="faq-question-1777716813546" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">map()したあとに結果を確認するにはどうすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>次のような方法で確認できます。<br /><code>df.head()</code> で変換前後の列を確認する<br /><code>value_counts(dropna=False)</code> で変換後の値の種類を確認する<br /><code>isnull().sum()</code> で <code>NaN</code> の数を確認する<br /><code>map()</code> は変換して終わりではなく、変換後の確認までセットで行うと安全です。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-map/">pandas 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-map/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>pandas cut()の使い方｜bins・labelsで数値を区間分けする方法を解説</title>
		<link>https://pythondatalab.com/pandas-cut/</link>
					<comments>https://pythondatalab.com/pandas-cut/#respond</comments>
		
		<dc:creator><![CDATA[coin_collector]]></dc:creator>
		<pubDate>Fri, 01 May 2026 17:34:33 +0000</pubDate>
				<category><![CDATA[抽出・前処理]]></category>
		<guid isPermaLink="false">https://pythondatalab.com/?p=1993</guid>

					<description><![CDATA[<p>pandasのcut()を使って、年齢・点数・購入金額などの数値を区間分けする方法を初心者向けに解説します。bins・labelsの指定、include_lowest、right、retbins、precision、qcutとの違い、NaNが出る原因まで具体例で学べます。</p>
<p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-cut/">pandas cut()の使い方｜bins・labelsで数値を区間分けする方法を解説</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.8em 0;
    padding: 0.8em 1em;
    overflow-x: auto;
    background: #f6f8fa;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
  }
  .colab-article .colab-output code {
    white-space: pre;
  }
  .colab-article .wp-block-table th,
  .colab-article .wp-block-table td {
    border: 1px solid #d9d9d9;
  }
  .colab-article .colab-figure {
    margin: 1em 0;
  }
  .colab-article .colab-figure img {
    max-width: 100%;
    height: auto;
  }
</style>
<script>Prism.highlightAll();</script>



<p>年齢、売上金額、点数のような数値データは、そのまま集計すると細かくなりすぎることがあります。</p>
<p>たとえば、年齢を1歳ごとに集計するよりも、<strong>10代・20代・30代</strong>のように分けた方が、全体の傾向を見やすい場面があります。売上金額も、1円単位で見るより、<strong>低価格・中価格・高価格</strong>のように価格帯で見た方が、分析しやすいことがあります。</p>
<p>このように、連続した数値を分析しやすい区間に分けたいときに使うのが、Pandasの<code>pd.cut()</code>です。</p>
<p>先に結論を言うと、<code>pd.cut()</code>は<strong>数値を「年代」「価格帯」「ランク」のようなカテゴリに分け、集計や可視化につなげるための前処理</strong>です。</p>
<p>たとえば、次のように考えると使いどころが分かりやすくなります。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>pd.cut()</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;">年齢</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>pd.cut()</code>は、数値をただ文字列に変える関数ではありません。<strong>細かい数値を、分析で使いやすいまとまりに変える関数</strong>です。</p>


  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-10" checked><label class="toc-title" for="toc-checkbox-10">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">この記事でわかること</a></li><li><a href="#toc2" tabindex="0">Pandas DataFrame入門シリーズの中での位置づけ</a></li><li><a href="#toc3" tabindex="0">pd.cut()とは何か</a></li><li><a href="#toc4" tabindex="0">pd.cut()の主な引数一覧</a></li><li><a href="#toc5" tabindex="0">サンプルデータを作成する</a></li><li><a href="#toc6" tabindex="0">年齢を年代に分ける基本例</a></li><li><a href="#toc7" tabindex="0">binsとlabelsの対応関係</a></li><li><a href="#toc8" tabindex="0">bins=3のように区間数だけ指定することもできる</a></li><li><a href="#toc9" tabindex="0">自動分割の境界値を確認したいときはretbins=True</a></li><li><a href="#toc10" tabindex="0">区間表示の小数が長いときはprecisionで見やすくできる</a></li><li><a href="#toc11" tabindex="0">処理前→処理後で見るcut()の結果</a></li><li><a href="#toc12" tabindex="0">value_counts()でカテゴリごとの件数を数える</a></li><li><a href="#toc13" tabindex="0">pd.cut()で区間分けした結果を棒グラフで可視化する</a></li><li><a href="#toc14" tabindex="0">groupby()でカテゴリ別に集計する</a></li><li><a href="#toc15" tabindex="0">点数をランクに分ける例</a></li><li><a href="#toc16" tabindex="0">売上金額・購入金額を価格帯に分ける例</a></li><li><a href="#toc17" tabindex="0">cut()・qcut()・np.where()の使い分け</a><ol><li><a href="#toc18" tabindex="0">qcut()は「個数をなるべく均等に分ける」</a></li><li><a href="#toc19" tabindex="0">np.where()は2択なら分かりやすい</a></li></ol></li><li><a href="#toc20" tabindex="0">境界値・NaN・よくあるミス</a><ol><li><a href="#toc21" tabindex="0">境界値はどちらの区間に入るのか</a></li><li><a href="#toc22" tabindex="0">right=Falseにすると左側の境界を含める</a></li><li><a href="#toc23" tabindex="0">最小値を含めたいときはinclude_lowest=True</a></li><li><a href="#toc24" tabindex="0">NaNが出る主な理由</a></li><li><a href="#toc25" tabindex="0">labelsの数が合わないとエラーになる</a></li></ol></li><li><a href="#toc26" tabindex="0">ヒストグラムのbinsとpd.cut()のbinsは同じですか？</a></li><li><a href="#toc27" tabindex="0">データ分析の流れの中でのpd.cut()の位置づけ</a></li><li><a href="#toc28" tabindex="0">まとめ：pd.cut()は数値を集計しやすいカテゴリに変える前処理</a></li><li><a href="#toc29" tabindex="0">関連記事：次に読むと理解しやすい記事</a><ol><li><a href="#toc30" tabindex="0"> カテゴリから探す</a></li><li><a href="#toc31" tabindex="0">pandasのcut()は何をする関数ですか？</a></li><li><a href="#toc32" tabindex="0">binsとlabelsは何を指定するものですか？</a></li><li><a href="#toc33" tabindex="0">labelsの数はいくつにすればよいですか？</a></li><li><a href="#toc34" tabindex="0">bins=3とは何ですか？</a></li><li><a href="#toc35" tabindex="0">include_lowest=Trueはいつ使いますか？</a></li><li><a href="#toc36" tabindex="0">pd.cut()でNaNが出るのはなぜですか？</a></li><li><a href="#toc37" tabindex="0">境界値の20や30はどちらの区間に入りますか？</a></li><li><a href="#toc38" tabindex="0">right=Falseはいつ使いますか？</a></li><li><a href="#toc39" tabindex="0">retbins=Trueはいつ使いますか？</a></li><li><a href="#toc40" tabindex="0">precisionは何を指定するものですか？</a></li><li><a href="#toc41" tabindex="0">cut()とqcut()の違いは何ですか？</a></li><li><a href="#toc42" tabindex="0">np.where()とcut()はどう使い分けますか？</a></li><li><a href="#toc43" tabindex="0">cut()で作ったカテゴリをvalue_counts()やgroupby()で使えますか？</a></li><li><a href="#toc44" tabindex="0">cut()で作ったカテゴリをグラフで確認できますか？</a></li><li><a href="#toc45" tabindex="0">ヒストグラムのbinsとpd.cut()のbinsは同じですか？</a></li></ol></li></ol>
    </div>
  </div>

<h2><span id="toc1">この記事でわかること</span></h2>
<p>この記事では、<code>pandas cut()</code>の使い方を、初心者が迷いやすいポイントに絞って解説します。</p>
<ul>
<li><code>pd.cut()</code>がどんな場面で役立つか</li>
<li><code>bins</code>と<code>labels</code>の意味</li>
<li><code>bins=3</code>のように、区間数だけ指定して分ける方法</li>
<li><code>bins=3</code>で区間表示に端数が出る理由</li>
<li><code>pd.cut()</code>でよく使う主な引数一覧</li>
<li><code>retbins=True</code>で自動分割された境界値を確認する方法</li>
<li><code>precision</code>で区間表示を見やすくするときの注意点</li>
<li><code>include_lowest=True</code>や<code>right=False</code>で境界値を調整する方法</li>
<li><code>cut()</code>、<code>qcut()</code>、<code>np.where()</code>の使い分け</li>
<li><code>pd.cut()</code>で作ったカテゴリを棒グラフで確認する方法</li>
<li><code>NaN</code>が出る理由と確認ポイント</li>
</ul>
<p>最初に結論を言うと、<code>pd.cut()</code>は<strong>数値を分析しやすいカテゴリに変える前処理</strong>です。<br/>
年齢、点数、購入金額のような数値を、年代・ランク・価格帯として集計したいときに役立ちます。</p>

<h2><span id="toc2">Pandas DataFrame入門シリーズの中での位置づけ</span></h2>
<p>このテーマは、Pandasの前処理と集計をつなぐ内容です。</p>
<p>まず<code>head()</code>、<code>info()</code>、<code>describe()</code>でデータを確認し、必要に応じて<code>astype()</code>や<code>fillna()</code>で整えます。その後、年齢や売上のような数値列を<code>pd.cut()</code>でカテゴリ化すると、<code>value_counts()</code>や<code>groupby()</code>で集計しやすくなります。</p>
<p>つまり、<code>pd.cut()</code>は次のような流れの中で使うと理解しやすいです。</p>
<p><strong>DataFrameの確認 → 型・欠損値の確認 → 数値列を区間分け → 件数集計・グループ集計 → 可視化</strong></p>

<h2><span id="toc3">pd.cut()とは何か</span></h2>
<p><code>pd.cut()</code>は、数値データを指定した区間ごとに分けるための関数です。</p>
<p>たとえば、次のような使い方ができます。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>pd.cut()</code>で作るカテゴリ</th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">18</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;">25</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">34</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">40代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">62</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>
<p>このように、細かい数値をそのまま使うのではなく、<strong>分析しやすいまとまりに変換する</strong>のが<code>pd.cut()</code>の役割です。</p>
<p>最初に判断基準を整理すると、次のようになります。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>pd.cut()</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>pd.qcut()</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;"><code>np.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>loc</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>
</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></td>
</tr>
</tbody>
</table></div>
<p>この記事では、特に「年齢を年代に分ける」「点数をランクに分ける」「価格帯ごとに集計する」といった、初心者が実際に使いやすい例に絞って解説します。</p>

<h2><span id="toc4">pd.cut()の主な引数一覧</span></h2>
<p><code>pd.cut()</code>にはいくつかの引数がありますが、初心者が最初にすべてを暗記する必要はありません。</p>
<p>まずは、<strong><code>bins</code>で区切り位置を決め、<code>labels</code>で分かりやすい名前を付ける</strong>と覚えると十分です。<br/>
そのうえで、境界値や自動分割で迷ったときに、<code>right</code>、<code>include_lowest</code>、<code>retbins</code>、<code>precision</code>を確認します。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>x</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">区間分けする数値データ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">DataFrameの列を指定することが多い</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>bins</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">区切り位置、または区間数</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">最重要。<code>[0, 19, 29]</code>のようなリストや、<code>3</code>のような区間数を指定できる</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>labels</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">区間につける名前</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">「10代以下」「20代」など、読者に伝わる名前にする</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>right</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">右側の境界を含めるか</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">初期設定は<code>True</code>。境界値で迷うときに確認する</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>include_lowest</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">最初の区間の下限を含めるか</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;"><code>retbins</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">実際に使われた境界値を返すか</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>bins=3</code>のような自動分割で、境界値を確認したいときに使う</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>precision</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>bins</code>と<code>labels</code>を中心に説明します。<br/>
その後で、必要に応じて<code>right</code>、<code>include_lowest</code>、<code>retbins</code>、<code>precision</code>も確認します。</p>

<h2><span id="toc5">サンプルデータを作成する</span></h2>
<p>まずは、Google Colabでそのまま実行できる小さなDataFrameを作ります。</p>
<p>今回は、名前、年齢、点数、購入金額を持つデータを使います。<br/>
年齢は年代分け、点数はランク分け、購入金額は価格帯分けに使います。</p>

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

df = pd.DataFrame({
    &quot;名前&quot;: [&quot;佐藤&quot;, &quot;田中&quot;, &quot;鈴木&quot;, &quot;高橋&quot;, &quot;伊藤&quot;, &quot;渡辺&quot;, &quot;山本&quot;, &quot;中村&quot;, &quot;小林&quot;, &quot;加藤&quot;],
    &quot;年齢&quot;: [18, 20, 24, 29, 30, 35, 42, 49, 55, 68],
    &quot;点数&quot;: [45, 62, 78, 88, 91, 55, 73, 69, 82, 96],
    &quot;購入金額&quot;: [800, 1500, 2400, 3200, 4800, 5200, 7600, 9100, 12000, 15000]
})

df</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</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;">18</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">45</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800</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;">62</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">1500</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;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">78</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2400</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;">88</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;">4</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;">91</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4800</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;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">55</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5200</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;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">73</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">7600</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;">49</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">69</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">9100</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;">55</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>
</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;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">68</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15000</td>
</tr>
</tbody>
</table></div>

<p>このデータには、次の3つの数値列があります。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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;">購入金額</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">価格帯に分ける</td>
</tr>
</tbody>
</table></div>
<p>数値列の型や欠損値を先に確認したい場合は、<code>info()</code>や<code>describe()</code>を使います。<br/>
型変換が必要な場合は、<code>astype()</code>で整えてから<code>cut()</code>を使うと安全です。</p>

<pre class="line-numbers"><code class="language-python">df.info()</code></pre>
<pre class="colab-output"><code>&lt;class &#x27;pandas.core.frame.DataFrame&#x27;&gt;
RangeIndex: 10 entries, 0 to 9
Data columns (total 4 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   名前      10 non-null     object
 1   年齢      10 non-null     int64 
 2   点数      10 non-null     int64 
 3   購入金額    10 non-null     int64 
dtypes: int64(3), object(1)
memory usage: 452.0+ bytes</code></pre>

<pre class="line-numbers"><code class="language-python">df.describe()</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</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;">count</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">10.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">mean</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">37.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">73.900000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">6160.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">std</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">16.295875</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">16.400881</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">4703.237656</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">min</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">18.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">45.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">25%</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">25.250000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">63.750000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2600.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">50%</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">32.500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">75.500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5000.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">75%</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">47.250000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">86.500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8725.000000</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">max</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">68.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">15000.000000</td>
</tr>
</tbody>
</table></div>

<h2><span id="toc6">年齢を年代に分ける基本例</span></h2>
<p>まずは、<code>pd.cut()</code>で年齢を年代に分けます。</p>
<p>基本形は次のように考えます。</p>
<pre><code class="language-python">pd.cut(分けたい数値列, bins=区切り位置, labels=区間名)
</code></pre>
<p>ここでは、年齢を次のように分けます。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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〜19歳</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;">20〜29歳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">30〜39歳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">40〜49歳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">50〜100歳</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>
<p>このように「自分で決めた範囲」で分けたいときに、<code>pd.cut()</code>が役立ちます。</p>

<pre class="line-numbers"><code class="language-python">age_bins = [0, 19, 29, 39, 49, 100]
age_labels = [&quot;10代以下&quot;, &quot;20代&quot;, &quot;30代&quot;, &quot;40代&quot;, &quot;50代以上&quot;]

df[&quot;年代&quot;] = pd.cut(
    df[&quot;年齢&quot;],
    bins=age_bins,
    labels=age_labels,
    include_lowest=True
)

df[[&quot;名前&quot;, &quot;年齢&quot;, &quot;年代&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</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;">18</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;">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;">20代</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;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">20代</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;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</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;">49</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</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;">55</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</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;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">68</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>

<p><code>年齢</code>列をもとに、<code>年代</code>列が新しく作られました。</p>
<p>ここでは、最初の区間の下限も含めるために<code>include_lowest=True</code>を指定しています。今回のサンプルでは0歳はありませんが、実データでは最小値が区間から外れて<code>NaN</code>になるのを防ぎやすくなります。</p>
<p>ここで大切なのは、<code>pd.cut()</code>が「新しい列を作る関数」そのものではないことです。<br/>
実際には、<code>pd.cut()</code>で作った結果を、<code>df["年代"] = ...</code>のようにDataFrameへ保存しています。</p>
<p>新しい列を追加する基本を詳しく確認したい場合は、<code>df['列名']</code>や<code>assign()</code>を扱う記事とあわせて読むと理解しやすくなります。</p>

<h2><span id="toc7">binsとlabelsの対応関係</span></h2>
<p><code>pd.cut()</code>で初心者が迷いやすいのが、<code>bins</code>と<code>labels</code>の数です。</p>
<p><code>bins</code>は区切り位置、<code>labels</code>は区間につける名前です。<br/>
<code>bins</code>の数と<code>labels</code>の数は同じではありません。</p>
<p>たとえば、次のように指定した場合を考えます。</p>
<pre><code class="language-python">bins = [0, 19, 29, 39, 49, 100]
labels = ["10代以下", "20代", "30代", "40代", "50代以上"]
</code></pre>
<p>対応関係は次のようになります。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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;"><code>bins</code>で作られる区間</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"><code>labels</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">0以上19以下</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;">19より大きく29以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">29より大きく39以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">39より大きく49以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">49より大きく100以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>
<p>区切り点が6個あると、区間は5個できます。<br/>
そのため、<code>labels</code>も5個必要です。</p>
<p>今回のように最初の区間の下限も含めたい場合は、<code>include_lowest=True</code>を指定しておくと安全です。たとえば、0歳や0点のような最小値を区間に含めたいときに役立ちます。</p>

<h2><span id="toc8">bins=3のように区間数だけ指定することもできる</span></h2>
<p><code>bins</code>には、区切り位置のリストだけでなく、区間の数を指定することもできます。</p>
<p>たとえば、次のように書くと、<code>点数</code>列を3つの区間に分けられます。</p>
<pre><code class="language-python">pd.cut(df["点数"], bins=3)
</code></pre>
<p>この書き方では、Pandasがデータの最小値と最大値をもとに、ほぼ同じ幅の区間を自動で作ります。<br/>
まず大まかに分布を分けて確認したいときには便利です。</p>
<p>ただし、自動分割では「60点以上は合格」「80点以上は高得点」のような意味のある基準になるとは限りません。<br/>
そのため、読者やチームに説明する列を作る場合は、<strong>自分で<code>bins=[0, 59, 79, 100]</code>のように区切り位置を指定し、<code>labels</code>で名前を付ける方が分かりやすい</strong>です。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;点数_3分割&quot;] = pd.cut(df[&quot;点数&quot;], bins=3)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;点数_3分割&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数_3分割</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;">45</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(44.949, 62.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;">62</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(44.949, 62.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;">78</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(62.0, 79.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;">88</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(79.0, 96.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;">91</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(79.0, 96.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;">55</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(44.949, 62.0]</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;">73</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(62.0, 79.0]</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;">69</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(62.0, 79.0]</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;">82</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(79.0, 96.0]</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;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">(79.0, 96.0]</td>
</tr>
</tbody>
</table></div>

<p><code>bins=3</code>では、Pandasが最小値から最大値までをもとに、ほぼ同じ幅の区間へ分けます。</p>
<p>このとき、最小値や最大値をきちんと含めるために、区間の端が少し調整されることがあります。<br/>
そのため、表示される区間名が <code>(44.949, 62.0]</code> のように端数を含む形になり、初心者には少し読みづらく見える場合があります。</p>
<p>ここで大事なのは、<code>bins=3</code>は<strong>自動でざっくり3分割する指定</strong>だということです。<br/>
「要復習」「標準」「高得点」のように意味を持たせたい場合は、<code>labels</code>を指定して分かりやすい名前を付けると読みやすくなります。</p>

<h2><span id="toc9">自動分割の境界値を確認したいときはretbins=True</span></h2>
<p><code>bins=3</code>のように区間数だけを指定した場合、Pandasが自動で区切り位置を決めます。</p>
<p>ただ、表示される区間だけを見ても、実際にどこで区切られているのか分かりにくいことがあります。<br/>
特に、区間表示に小数が出ている場合は、「なぜこの数字になったのか」が気になりやすいです。</p>
<p>その場合は、<code>retbins=True</code>を使うと、実際に使われた境界値を確認できます。</p>

<pre class="line-numbers"><code class="language-python">score_categories, score_bins = pd.cut(
    df[&quot;点数&quot;],
    bins=3,
    retbins=True
)

score_bins</code></pre>
<pre class="colab-output"><code>array([44.949, 62.   , 79.   , 96.   ])</code></pre>

<p><code>retbins=True</code>を指定すると、カテゴリ分けの結果と、実際に使われた境界値が返ります。</p>
<p>初心者のうちは必須ではありません。<br/>
ただし、<code>bins=3</code>のような自動分割を使ったときに、<strong>どこで区切られたのかを確認したい場合</strong>に便利です。</p>
<p>記事やレポートで結果を説明するなら、自動分割のまま使うより、境界値を確認したうえで<code>bins=[0, 59, 79, 100]</code>のように明示的な基準へ直す方が伝わりやすい場合もあります。</p>

<h2><span id="toc10">区間表示の小数が長いときはprecisionで見やすくできる</span></h2>
<p><code>bins=3</code>のような自動分割では、区間が小数で表示されることがあります。</p>
<p>たとえば、<code>(44.949, 62.0]</code>のような表示は、初心者には少し読みにくいかもしれません。<br/>
このようなときは、<code>precision</code>で区間ラベルに表示される境界値の桁数を調整できます。</p>
<p>ただし、<code>precision</code>は<strong>元データの点数を丸める指定ではありません</strong>。<br/>
あくまで、<code>pd.cut()</code>で作られる区間表示を見やすくするための指定だと考えると分かりやすいです。</p>
<p>分析の基準を明確にしたい場合は、<code>precision</code>で見た目を整えるよりも、<code>bins=[0, 59, 79, 100]</code>のように自分で区切り位置を決め、<code>labels=["要復習", "標準", "高得点"]</code>のように名前を付ける方が実務では伝わりやすくなります。</p>

<pre class="line-numbers"><code class="language-python">pd.cut(df[&quot;点数&quot;], bins=3, precision=1)</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数</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;">(44.9, 62.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;">(44.9, 62.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;">(62.0, 79.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;">(79.0, 96.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;">(79.0, 96.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;">(44.9, 62.0]</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;">(62.0, 79.0]</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;">(62.0, 79.0]</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;">(79.0, 96.0]</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;">(79.0, 96.0]</td>
</tr>
</tbody>
</table></div>

<p>上の例では、区間表示が少し短くなります。</p>
<p>ただし、<code>precision</code>を指定しても、元の<code>点数</code>列そのものが丸められるわけではありません。<br/>
また、「何点から何点までをどのランクにするか」という分析上の基準を決める指定でもありません。</p>
<p>そのため、初心者のうちは次のように使い分けると安全です。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>precision</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>bins</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>labels</code>を指定する</td>
</tr>
</tbody>
</table></div>

<h2><span id="toc11">処理前→処理後で見るcut()の結果</span></h2>
<p><code>pd.cut()</code>の役割は、処理前と処理後で見ると分かりやすいです。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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;">18</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;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">49</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">68</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>
<p>コードでも、処理前と処理後を並べて確認してみます。</p>

<pre class="line-numbers"><code class="language-python">before_after = pd.DataFrame({
    &quot;処理前_年齢&quot;: df[&quot;年齢&quot;],
    &quot;処理後_年代&quot;: df[&quot;年代&quot;]
})

before_after</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">処理前_年齢</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;">18</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">24</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">35</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">42</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</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;">49</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40代</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;">55</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</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;">68</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
</tr>
</tbody>
</table></div>

<p><code>pd.cut()</code>を使うと、数値列をそのまま残しつつ、分析用のカテゴリ列を追加できます。</p>
<p>年齢の数値そのものを消してしまうのではなく、<code>年齢</code>列と<code>年代</code>列の両方を残すと、あとから確認しやすくなります。</p>

<h2><span id="toc12">value_counts()でカテゴリごとの件数を数える</span></h2>
<p><code>pd.cut()</code>で年代列を作ったら、次に知りたくなるのは「各年代に何人いるか」です。</p>
<p>このときは、<code>value_counts()</code>を使います。</p>
<p>ここでの主役は<code>pd.cut()</code>で作ったカテゴリ列です。<br/>
<code>value_counts()</code>はカテゴリを作る関数ではなく、<strong>作ったカテゴリの件数を数える関数</strong>です。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;年代&quot;].value_counts(sort=False)</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">count</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">年代</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">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;">20代</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;">2</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;">2</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">50代以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
</tbody>
</table></div>

<p><code>sort=False</code>を指定すると、カテゴリの順番に近い形で表示されます。</p>
<p>年代別の件数を見たい場合は、次のような流れになります。</p>
<ol>
<li><code>pd.cut()</code>で年代列を作る</li>
<li><code>value_counts()</code>で年代ごとの件数を数える</li>
</ol>
<p>件数集計そのものを詳しく学びたい場合は、<code>value_counts()</code>の記事に進むと理解しやすいです。</p>

<h2><span id="toc13">pd.cut()で区間分けした結果を棒グラフで可視化する</span></h2>
<p><code>value_counts()</code>で件数を確認できたら、棒グラフにすると「どの区間にデータが多いのか」をさらに確認しやすくなります。</p>
<p>ここで大切なのは、グラフが主役ではなく、<strong><code>pd.cut()</code>で作ったカテゴリ列を確認するための補助として使う</strong>ことです。</p>
<p>今回は、年代ごとの人数を棒グラフで見てみます。<br/>
なお、ColabやWordPressの表示環境によって日本語が文字化けすることを避けるため、グラフ用の横軸ラベルだけ英数字に置き換えています。元の<code>年代</code>列は日本語のままです。</p>

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

# pd.cut()で作った「年代」列を集計
age_counts = df[&quot;年代&quot;].value_counts(sort=False)

# グラフ表示用に、横軸ラベルだけ英数字へ置き換える
age_counts_for_plot = age_counts.copy()
age_counts_for_plot.index = [&quot;under_19&quot;, &quot;20s&quot;, &quot;30s&quot;, &quot;40s&quot;, &quot;50_plus&quot;]

ax = age_counts_for_plot.plot(kind=&quot;bar&quot;)
ax.set_title(&quot;Count by age group&quot;)
ax.set_xlabel(&quot;Age group&quot;)
ax.set_ylabel(&quot;Count&quot;)

plt.tight_layout()
plt.show()</code></pre>
<figure class="colab-figure">
  <img decoding="async" src="https://pythondatalab.com/wp-content/uploads/2026/05/pandas-cut-graph.png" alt="pd.cut()で区間分けしたカテゴリの件数を示す棒グラフ">
  <figcaption>pd.cut()で作ったカテゴリの件数を棒グラフで確認する例</figcaption>
</figure>
<p>棒グラフにすると、<code>pd.cut()</code>で作ったカテゴリごとの人数を視覚的に確認できます。</p>
<p>表だけでも件数は分かりますが、グラフにすると「どの区間が多いのか」「少ない区間はどこか」が一目で分かりやすくなります。</p>
<p>ただし、この記事の主役はMatplotlibではありません。<br/>
まずは、<code>pd.cut()</code>でカテゴリ列を作り、<code>value_counts()</code>で件数を確認し、必要に応じて棒グラフで見やすくする、という流れで考えると十分です。</p>

<h2><span id="toc14">groupby()でカテゴリ別に集計する</span></h2>
<p><code>pd.cut()</code>で作ったカテゴリ列は、<code>groupby()</code>にも使えます。</p>
<p>たとえば、年代ごとに平均点や平均購入金額を見たい場合です。</p>

<pre class="line-numbers"><code class="language-python">df.groupby(&quot;年代&quot;, observed=True).agg(
    平均点=(&quot;点数&quot;, &quot;mean&quot;),
    平均購入金額=(&quot;購入金額&quot;, &quot;mean&quot;),
    人数=(&quot;名前&quot;, &quot;count&quot;)
)</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">平均点</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">平均購入金額</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">人数</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">年代</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">10代以下</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">45.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">800.000000</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;">20代</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">76.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2366.666667</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;">73.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">5000.000000</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;">40代</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">71.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">8350.000000</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;">50代以上</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">89.0</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">13500.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">2</td>
</tr>
</tbody>
</table></div>

<p><code>年代</code>ごとに、平均点・平均購入金額・人数を集計できました。</p>
<p>このように、<code>pd.cut()</code>は集計の前準備として使うと便利です。<br/>
<code>groupby()</code>そのものが主役ではなく、ここでは<strong>集計しやすいカテゴリを先に作る</strong>ことがポイントです。</p>
<p>ここでは、<code>groupby()</code>に<code>observed=True</code>を指定しています。これは、カテゴリ列を集計するときに、実際にデータに存在するカテゴリを中心に表示するための指定です。初心者のうちは、<code>pd.cut()</code>で作ったカテゴリ列を<code>groupby()</code>する場合は、この形で確認すれば大丈夫です。</p>

<h2><span id="toc15">点数をランクに分ける例</span></h2>
<p>次に、点数をランクに分けてみます。</p>
<p>ここでは、点数を次の3つに分けます。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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〜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;">60〜79点</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;">80〜100点</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">高得点</td>
</tr>
</tbody>
</table></div>
<p>点数のように、一定の基準でランク分けしたい場合にも<code>pd.cut()</code>が使えます。</p>
<p>ここでは下限の0点も「要復習」に含めたいので、<code>include_lowest=True</code>を指定します。<br/>
この指定を入れておくと、<code>bins</code>の最初の値と同じデータが<code>NaN</code>になりにくくなります。</p>

<pre class="line-numbers"><code class="language-python">score_bins = [0, 59, 79, 100]
score_labels = [&quot;要復習&quot;, &quot;標準&quot;, &quot;高得点&quot;]

df[&quot;点数ランク&quot;] = pd.cut(
    df[&quot;点数&quot;],
    bins=score_bins,
    labels=score_labels,
    include_lowest=True
)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;点数ランク&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</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;">45</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;">62</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;">78</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;">88</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;">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;">5</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;">6</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>
<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;">69</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;">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;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">高得点</td>
</tr>
</tbody>
</table></div>

<p>点数をランクに分けると、1点ごとの差ではなく、全体の傾向を見やすくなります。</p>
<p>たとえば、どのランクの人数が多いかを確認できます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;点数ランク&quot;].value_counts(sort=False)</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">count</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">点数ランク</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</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;">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;">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;">4</td>
</tr>
</tbody>
</table></div>

<h2><span id="toc16">売上金額・購入金額を価格帯に分ける例</span></h2>
<p>購入金額や売上金額も、<code>pd.cut()</code>と相性がよい列です。</p>
<p>ここでは、購入金額を次のように価格帯に分けます。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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〜2,000円</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,001〜5,000円</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,001〜10,000円</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;">10,001〜20,000円</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">かなり高い</td>
</tr>
</tbody>
</table></div>
<p>金額をそのまま1円単位で集計するより、価格帯で見る方が傾向をつかみやすいことがあります。</p>
<p>購入金額でも、0円を下限として含めたい場合は<code>include_lowest=True</code>を指定しておくと安全です。<br/>
特に「0〜2,000円」のように表で説明している場合は、コード側も下限を含める形にそろえると読み手が迷いにくくなります。</p>

<pre class="line-numbers"><code class="language-python">price_bins = [0, 2000, 5000, 10000, 20000]
price_labels = [&quot;低価格&quot;, &quot;中価格&quot;, &quot;高価格&quot;, &quot;かなり高い&quot;]

df[&quot;価格帯&quot;] = pd.cut(
    df[&quot;購入金額&quot;],
    bins=price_bins,
    labels=price_labels,
    include_lowest=True
)

df[[&quot;名前&quot;, &quot;購入金額&quot;, &quot;価格帯&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</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;">800</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;">1500</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;">2400</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;">3200</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;">4800</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;">5200</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;">7600</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;">9100</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;">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;">9</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;">かなり高い</td>
</tr>
</tbody>
</table></div>

<p>作成した<code>価格帯</code>列を使うと、価格帯ごとの人数や平均点などを確認できます。</p>

<pre class="line-numbers"><code class="language-python">df.groupby(&quot;価格帯&quot;, observed=True).agg(
    人数=(&quot;名前&quot;, &quot;count&quot;),
    平均点=(&quot;点数&quot;, &quot;mean&quot;),
    平均年齢=(&quot;年齢&quot;, &quot;mean&quot;)
)</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">人数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">平均点</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">平均年齢</th>
</tr>
<tr>
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">価格帯</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;"></th>
</tr>
</thead>
<tbody>
<tr>
<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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">53.500000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">19.000000</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;">85.666667</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">27.666667</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;">65.666667</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">42.000000</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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">89.000000</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">61.500000</td>
</tr>
</tbody>
</table></div>

<h2><span id="toc17">cut()・qcut()・np.where()の使い分け</span></h2>
<p><code>pd.cut()</code>に近いものとして、<code>pd.qcut()</code>や<code>np.where()</code>があります。</p>
<p>ここで大切なのは、どれが上位互換という話ではなく、<strong>目的によって使い分ける</strong>ことです。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>pd.cut()</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">自分で決めた区間で分けたい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>bins</code>と<code>labels</code>の数、境界値</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>pd.qcut()</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>np.where()</code></td>
<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="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>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">複数条件を書くときに少し複雑になる</td>
</tr>
</tbody>
</table></div>
<p>年齢を「10代・20代・30代」のように、自分で決めた範囲で分けたいなら<code>cut()</code>が分かりやすいです。</p>
<p>一方で、点数を「人数がなるべく同じになるように3グループへ分けたい」という場合は、<code>qcut()</code>が候補になります。</p>

<h3><span id="toc18">qcut()は「個数をなるべく均等に分ける」</span></h3>
<p><code>qcut()</code>は、区間の幅を自分で決めるというより、データの個数がなるべく均等になるように分けます。</p>
<p>ここでは、詳しい使い方には深入りせず、<code>cut()</code>との考え方の違いだけ確認します。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;点数_qcut_3分割&quot;] = pd.qcut(df[&quot;点数&quot;], q=3, labels=[&quot;低め&quot;, &quot;中くらい&quot;, &quot;高め&quot;])

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;点数_qcut_3分割&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数_qcut_3分割</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;">45</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;">62</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;">78</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;">88</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;">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;">5</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;">6</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>
<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;">69</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;">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;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">高め</td>
</tr>
</tbody>
</table></div>

<p><code>qcut()</code>では、点数の区間幅が同じになるとは限りません。<br/>
「各グループに入るデータ数をなるべく近づけたい」ときに使います。</p>
<p>一方、この記事の主役である<code>cut()</code>は、<strong>自分で決めた区間</strong>で分けたいときに使います。</p>

<h3><span id="toc19">np.where()は2択なら分かりやすい</span></h3>
<p>たとえば、点数が60点以上なら「合格」、それ以外なら「要復習」とするだけなら、<code>np.where()</code>でも分かりやすく書けます。</p>

<pre class="line-numbers"><code class="language-python">df[&quot;合否&quot;] = np.where(df[&quot;点数&quot;] &gt;= 60, &quot;合格&quot;, &quot;要復習&quot;)

df[[&quot;名前&quot;, &quot;点数&quot;, &quot;合否&quot;]]</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">名前</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;">45</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;">62</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;">78</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;">88</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;">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;">5</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;">6</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>
<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;">69</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;">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;">9</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">加藤</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">96</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">合格</td>
</tr>
</tbody>
</table></div>

<p>ただし、「要復習・標準・高得点」のように複数の数値区間に分けたい場合は、<code>pd.cut()</code>の方が読みやすくなりやすいです。</p>
<p>2択なら<code>np.where()</code>、複数の数値区間なら<code>pd.cut()</code>と考えると、初心者でも判断しやすくなります。</p>

<h2><span id="toc20">境界値・NaN・よくあるミス</span></h2>
<p><code>pd.cut()</code>で特につまずきやすいのは、次の3つです。</p>
<ol>
<li>境界値がどちらの区間に入るか</li>
<li><code>NaN</code>が出る理由</li>
<li><code>bins</code>と<code>labels</code>の数が合わないエラー</li>
</ol>
<p>順番に確認します。</p>

<h3><span id="toc21">境界値はどちらの区間に入るのか</span></h3>
<p><code>pd.cut()</code>は、初期設定では右側の境界を含みます。<br/>
つまり、<code>right=True</code>が標準です。</p>
<p>たとえば、<code>bins=[0, 19, 29, 39]</code>の場合、基本的には次のように考えます。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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;">19</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;">20</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">30代</td>
</tr>
</tbody>
</table></div>
<p>実際に確認してみます。</p>

<pre class="line-numbers"><code class="language-python">boundary_df = pd.DataFrame({
    &quot;年齢&quot;: [19, 20, 29, 30, 39]
})

boundary_df[&quot;年代&quot;] = pd.cut(
    boundary_df[&quot;年齢&quot;],
    bins=[0, 19, 29, 39],
    labels=[&quot;10代以下&quot;, &quot;20代&quot;, &quot;30代&quot;]
)

boundary_df</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</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;">19</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;">1</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">39</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
</tr>
</tbody>
</table></div>

<p>このように、境界値を含む場合は、実際に小さなデータで確認すると安心です。</p>
<p>「20は20代に入るのか」「30は30代に入るのか」と迷ったときは、境界値だけのDataFrameを作って試すのがおすすめです。</p>

<h3><span id="toc22">right=Falseにすると左側の境界を含める</span></h3>
<p>初期設定の<code>right=True</code>では、右側の境界を含みます。<br/>
一方で、<code>right=False</code>を指定すると、左側の境界を含む形になります。</p>
<p>たとえば、年齢を次のように考えたい場合です。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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;">20以上30未満</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;">30以上40未満</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</td>
</tr>
</tbody>
</table></div>
<p>このように、「20歳以上30歳未満」のような表現にしたいときは、<code>right=False</code>が分かりやすいです。</p>

<pre class="line-numbers"><code class="language-python">right_false_df = pd.DataFrame({
    &quot;年齢&quot;: [19, 20, 29, 30, 39, 40]
})

right_false_df[&quot;年代_right_false&quot;] = pd.cut(
    right_false_df[&quot;年齢&quot;],
    bins=[0, 20, 30, 40],
    labels=[&quot;20歳未満&quot;, &quot;20代&quot;, &quot;30代&quot;],
    right=False
)

right_false_df</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年齢</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">年代_right_false</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;">19</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20歳未満</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;">20</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">29</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">20代</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;">30</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">39</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">30代</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;">40</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
</tbody>
</table></div>

<p><code>right=False</code>にすると、20は「20代」、30は「30代」に入ります。<br/>
ただし、最後の区間は「30以上40未満」になるため、40は範囲外となり<code>NaN</code>になります。</p>
<p>このように、<code>right=False</code>を使う場合も、最大値が区間から外れていないかを確認することが大切です。<br/>
迷ったときは、実データの最小値・最大値と、境界値だけを小さなDataFrameで確認すると安全です。</p>

<h3><span id="toc23">最小値を含めたいときはinclude_lowest=True</span></h3>
<p><code>pd.cut()</code>では、最初の区間の左端が含まれないことで迷う場合があります。</p>
<p>たとえば、0点を含めたいときには、<code>include_lowest=True</code>を指定すると分かりやすくなります。</p>

<pre class="line-numbers"><code class="language-python">score_check = pd.DataFrame({
    &quot;点数&quot;: [0, 1, 59, 60]
})

score_check[&quot;ランク_include_lowestなし&quot;] = pd.cut(
    score_check[&quot;点数&quot;],
    bins=[0, 59, 100],
    labels=[&quot;要復習&quot;, &quot;合格&quot;]
)

score_check[&quot;ランク_include_lowestあり&quot;] = pd.cut(
    score_check[&quot;点数&quot;],
    bins=[0, 59, 100],
    labels=[&quot;要復習&quot;, &quot;合格&quot;],
    include_lowest=True
)

score_check</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">ランク_include_lowestなし</th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">ランク_include_lowestあり</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;">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;">1</td>
<td style="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>
</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;">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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">60</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>0点のように、最初の区切り位置そのものを含めたい場合は、<code>include_lowest=True</code>を検討します。</p>
<p>特に点数、金額、年齢のように最小値が意味を持つデータでは、最小値が<code>NaN</code>になっていないか確認しましょう。</p>

<h3><span id="toc24">NaNが出る主な理由</span></h3>
<p><code>pd.cut()</code>で<code>NaN</code>が出る主な理由は、次のとおりです。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>bins</code>の最小値より小さい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>bins</code>が0からなのに、値が-1</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>bins</code>の最大値より大きい</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>bins</code>が100までなのに、値が120</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>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;">最小値0が区間に入っていない</td>
</tr>
<tr>
<td style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"><code>right=False</code>で最後の境界値が外れる</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">40未満の区間に40が入らない</td>
</tr>
</tbody>
</table></div>
<p>実際に、<code>bins</code>の範囲外の値がある例を確認します。</p>

<pre class="line-numbers"><code class="language-python">nan_df = pd.DataFrame({
    &quot;点数&quot;: [-5, 0, 50, 85, 120, np.nan]
})

nan_df[&quot;ランク&quot;] = pd.cut(
    nan_df[&quot;点数&quot;],
    bins=[0, 59, 79, 100],
    labels=[&quot;要復習&quot;, &quot;標準&quot;, &quot;高得点&quot;],
    include_lowest=True
)

nan_df</code></pre>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><table class="wp-block-table" style="width: auto; border-collapse: collapse;">
<thead>
<tr style="text-align: right;">
<th style="min-width: 3em; white-space: nowrap; padding: 0.2em 0.4em;"></th>
<th style="white-space: nowrap; padding: 0.2em 0.4em;">点数</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;">-5.0</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;">0.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;">2</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">50.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;">3</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">85.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;">4</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">120.0</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;">NaN</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">NaN</td>
</tr>
</tbody>
</table></div>

<p>この例では、<code>-5</code>や<code>120</code>は指定した<code>bins</code>の範囲外なので<code>NaN</code>になります。<br/>
元の値が<code>NaN</code>の場合も、結果は<code>NaN</code>になります。</p>
<p><code>pd.cut()</code>で<code>NaN</code>が出たときは、まず次の点を確認しましょう。</p>
<ul>
<li><code>bins</code>の範囲がデータ全体をカバーしているか</li>
<li>最小値を含める必要があるか</li>
<li>元データに欠損値があるか</li>
</ul>

<h3><span id="toc25">labelsの数が合わないとエラーになる</span></h3>
<p><code>labels</code>の数は、区間の数と同じにする必要があります。</p>
<p>たとえば、<code>bins=[0, 59, 79, 100]</code>なら区間は3つなので、<code>labels</code>も3つ必要です。</p>
<p>次のコードでは、あえて<code>labels</code>の数を間違えて、どのようなエラーになるかを確認します。<br/>
エラーでNotebookが止まらないように、<code>try</code>と<code>except</code>で表示だけ行います。</p>

<pre class="line-numbers"><code class="language-python">try:
    pd.cut(
        df[&quot;点数&quot;],
        bins=[0, 59, 79, 100],
        labels=[&quot;要復習&quot;, &quot;標準&quot;]  # 本来は3つ必要
    )
except ValueError as e:
    print(&quot;エラー内容:&quot;)
    print(e)</code></pre>
<pre class="colab-output"><code>エラー内容:
Bin labels must be one fewer than the number of bin edges</code></pre>

<p>このようなエラーが出た場合は、<code>bins</code>から作られる区間の数と、<code>labels</code>の数が合っているかを確認します。</p>
<p>覚え方は次のとおりです。</p>
<pre><code class="language-text">labelsの数 = binsの数 - 1
</code></pre>
<p>ただし、これは基本的な考え方です。細かいオプションを使う場合は例外もあるため、初心者のうちはまず基本形で覚えるのがおすすめです。</p>

<h2><span id="toc26">ヒストグラムのbinsとpd.cut()のbinsは同じですか？</span></h2>
<p>ヒストグラムにも<code>bins</code>という言葉が出てきます。<br/>
<code>pd.cut()</code>にも<code>bins</code>があります。</p>
<p>どちらも「数値を区間で分ける」という考え方は近いです。<br/>
ただし、目的が少し違います。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>bins</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>pd.cut()</code>の<code>bins</code></td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">区間カテゴリをデータ列として作る</td>
</tr>
</tbody>
</table></div>
<p>ヒストグラムは、数値の分布を可視化したいときに使います。<br/>
<code>pd.cut()</code>は、区間ごとのカテゴリ列を作り、その後の<code>value_counts()</code>や<code>groupby()</code>につなげたいときに使います。</p>
<p>分布をグラフで確認したい場合は、ヒストグラムや箱ひげ図の記事に進むと理解しやすくなります。</p>

<h2><span id="toc27">データ分析の流れの中でのpd.cut()の位置づけ</span></h2>
<p><code>pd.cut()</code>は、単独で覚えるよりも、データ分析の流れの中で考えると使いどころが分かりやすくなります。</p>
<div class="colab-table-wrap" style="overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0.8em 0;"><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>head()</code>、<code>info()</code>、<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;">データを整える</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;"><code>astype()</code>、<code>fillna()</code>、<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>pd.cut()</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()</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;">ヒストグラム、棒グラフ</td>
<td style="white-space: nowrap; padding: 0.2em 0.4em;">分布やカテゴリ別の違いを見る</td>
</tr>
</tbody>
</table></div>
<p>この記事の主役は、3つ目の「数値をカテゴリ化する」部分です。</p>
<p>列を作る方法そのものを詳しく知りたい場合は「新しい列を追加する方法」、カテゴリごとの件数を詳しく知りたい場合は「value_counts()」、カテゴリ別の平均や合計を出したい場合は「groupby×agg」に進むと、学習の流れがつながります。</p>

<h2><span id="toc28">まとめ：pd.cut()は数値を集計しやすいカテゴリに変える前処理</span></h2>
<p>この記事では、<code>pandas cut()</code>の使い方を、年齢・点数・購入金額の例で解説しました。</p>
<p>大事なポイントを整理します。</p>
<ul>
<li><code>pd.cut()</code>は、連続した数値を区間ごとのカテゴリに分ける関数</li>
<li><code>bins</code>は区切り位置、<code>labels</code>は区間名</li>
<li><code>bins=3</code>のように区間数だけ指定することもできる</li>
<li><code>bins=3</code>では、Pandasがデータの最小値と最大値をもとに、ほぼ同じ幅の区間を自動で作る</li>
<li>自動分割では、区間表示に端数が出ることがある</li>
<li><code>retbins=True</code>を使うと、自動分割された境界値を確認できる</li>
<li><code>precision</code>は、区間表示を見やすくする指定であり、元データを丸める指定ではない</li>
<li><code>labels</code>の数は、基本的に<code>bins</code>の数より1つ少なくする</li>
<li>年齢を年代、点数をランク、金額を価格帯に分けると集計しやすくなる</li>
<li><code>cut()</code>で作ったカテゴリは、<code>value_counts()</code>や<code>groupby()</code>に使える</li>
<li><code>value_counts()</code>の結果を棒グラフにすると、カテゴリごとの違いを視覚的に確認できる</li>
<li><code>qcut()</code>は、データ数がなるべく均等になるように分けたいときの候補</li>
<li>2択なら<code>np.where()</code>、複数の数値区間なら<code>pd.cut()</code>が分かりやすい</li>
<li><code>NaN</code>が出たら、<code>bins</code>の範囲、元データの欠損、境界値、<code>right</code>の指定を確認する</li>
<li>下限の0点・0円などを区間に含めたい場合は、<code>include_lowest=True</code>を指定すると安全</li>
<li>「20以上30未満」のように左側を含めたい場合は、<code>right=False</code>も候補になる</li>
</ul>
<p><code>pd.cut()</code>は、派手な関数ではありませんが、数値データを「分析しやすい形」に変えるためにとても便利です。</p>
<p>CSVを読み込んだあと、年齢・点数・売上金額のような数値列を見つけたら、まずは「そのまま集計するのか」「区間に分けた方が見やすいのか」を考えてみてください。</p>

<h2><span id="toc29">関連記事：次に読むと理解しやすい記事</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-add-column/">pandasで新しい列を追加する方法｜df[&#8216;列名&#8217;]・assign・条件付き列追加を初心者向けに解説</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>
<li><a href="https://pythondatalab.com/matplotlib-hist-boxplot/">Matplotlib ヒストグラム＆箱ひげ図 入門｜bins設定と外れ値の可視化・分析</a></li>
</ul>
<p>特に、<code>pd.cut()</code>で作ったカテゴリ列は、<code>value_counts()</code>や<code>groupby()</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="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>

</div>



<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-1777656549532" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc31">pandasのcut()は何をする関数ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>pd.cut()</code>は、数値データを指定した区間に分ける関数です。<br />たとえば、年齢を「10代以下・20代・30代」、点数を「要復習・標準・高得点」、購入金額を「低価格・中価格・高価格」のように分けられます。</p>

</div>
</div>
<div id="faq-question-1777656566381" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc32">binsとlabelsは何を指定するものですか？</span></h3>
<div class="rank-math-answer ">

<p><code>bins</code>は区切り位置、<code>labels</code>は区間につける名前です。<br />たとえば、<code>bins=[0, 19, 29, 39]</code>なら区間は3つできるため、<code>labels</code>も3つ指定します。</p>

</div>
</div>
<div id="faq-question-1777656582060" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc33">labelsの数はいくつにすればよいですか？</span></h3>
<div class="rank-math-answer ">

<p>基本的には、<code>labels</code>の数は<code>bins</code>の数より1つ少なくします。<br /><code>bins</code>が4個なら区間は3つなので、<code>labels</code>は3個です。</p>

</div>
</div>
<div id="faq-question-1777656596439" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc34">bins=3とは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>bins=3</code>は、数値列を3つの区間に分ける指定です。<br />Pandasがデータの最小値と最大値をもとに、ほぼ同じ幅の区間を自動で作ります。<br />大まかに分けて確認したいときは便利ですが、年代や点数ランクのように意味のある区切りを使いたい場合は、<code>bins=[0, 59, 79, 100]</code>のように自分で指定する方が分かりやすいです。<br />また、自動分割では区間表示に端数が出ることがあります。気になる場合は<code>retbins=True</code>で境界値を確認します。</p>

</div>
</div>
<div id="faq-question-1777656610687" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc35">include_lowest=Trueはいつ使いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>include_lowest=True</code>は、最初の区間の下限も含めたいときに使います。<br />たとえば、<code>bins=[0, 59, 79, 100]</code>で「0〜59点」を要復習にしたい場合、0点も含めるために指定しておくと安全です。</p>

</div>
</div>
<div id="faq-question-1777656624893" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc36">pd.cut()でNaNが出るのはなぜですか？</span></h3>
<div class="rank-math-answer ">

<p>主な理由は、値が<code>bins</code>の範囲外にあることです。<br />たとえば、<code>bins</code>を0〜100で指定しているのに、値が120なら<code>NaN</code>になります。元データが欠損している場合も<code>NaN</code>になります。</p>

</div>
</div>
<div id="faq-question-1777656646045" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc37">境界値の20や30はどちらの区間に入りますか？</span></h3>
<div class="rank-math-answer ">

<p>初期設定では、<code>pd.cut()</code>は右側の境界を含みます。<br />たとえば、<code>bins=[0, 19, 29, 39]</code>なら、20は20代の区間、30は30代の区間に入ります。迷ったときは、境界値だけの小さなDataFrameで確認するのがおすすめです</p>

</div>
</div>
<div id="faq-question-1777656660502" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc38">right=Falseはいつ使いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>right=False</code>は、「20以上30未満」のように左側の境界を含めたいときに使います。<br />初期設定では右側の境界を含むため、境界値がどちらの区間に入るかで迷ったときは、<code>right=True</code>と<code>right=False</code>の結果を小さなデータで確認すると安心です。</p>

</div>
</div>
<div id="faq-question-1777656682012" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc39">retbins=Trueはいつ使いますか？</span></h3>
<div class="rank-math-answer ">

<p><code>retbins=True</code>は、<code>bins=3</code>のように区間数だけを指定したときに、Pandasが実際にどの境界値で区切ったのか確認したい場合に使います。<br />初心者のうちは必須ではありませんが、自動分割の結果を確認したいときに便利です。</p>

</div>
</div>
<div id="faq-question-1777656698828" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc40">precisionは何を指定するものですか？</span></h3>
<div class="rank-math-answer ">

<p><code>precision</code>は、区間ラベルに表示される境界値の桁数を調整する指定です。<br /><code>bins=3</code>のような自動分割では区間表示が小数になることがあるため、見た目を少し整えたいときに使えます。<br />ただし、<code>precision</code>は元データを丸める指定ではありません。<br />分析上の区切りを明確にしたい場合は、<code>precision</code>で見た目を整えるより、自分で<code>bins</code>を指定する方が分かりやすいです。</p>

</div>
</div>
<div id="faq-question-1777656713140" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc41">cut()とqcut()の違いは何ですか？</span></h3>
<div class="rank-math-answer ">

<p><code>cut()</code>は、自分で決めた区間で分けたいときに使います。<br /><code>qcut()</code>は、データの個数がなるべく均等になるように分けたいときに使います。年代や価格帯のように範囲を自分で決めたいなら、まずは<code>cut()</code>が分かりやすいです。</p>

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

<p>2択の条件分岐なら<code>np.where()</code>が分かりやすいです。<br />たとえば、60点以上なら「合格」、それ以外なら「要復習」のような場合です。一方で、「要復習・標準・高得点」のように複数の数値区間に分けたい場合は、<code>pd.cut()</code>の方が読みやすくなります。</p>

</div>
</div>
<div id="faq-question-1777656745629" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc43">cut()で作ったカテゴリをvalue_counts()やgroupby()で使えますか？</span></h3>
<div class="rank-math-answer ">

<p>はい、使えます。<br /><code>pd.cut()</code>で年代や価格帯の列を作り、その列に対して<code>value_counts()</code>を使うとカテゴリごとの件数を確認できます。さらに、<code>groupby()</code>を使うと、年代ごとの平均点や価格帯ごとの平均購入金額のような集計もできます。</p>

</div>
</div>
<div id="faq-question-1777656764957" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc44">cut()で作ったカテゴリをグラフで確認できますか？</span></h3>
<div class="rank-math-answer ">

<p>はい、確認できます。<br /><code>pd.cut()</code>で作ったカテゴリ列に対して<code>value_counts()</code>を使い、その結果を棒グラフにすると、カテゴリごとの件数を視覚的に確認できます。<br />ただし、<code>pd.cut()</code>の記事ではグラフを増やしすぎる必要はありません。<br />まずは「カテゴリ列を作る」「件数を数える」「必要なら棒グラフで確認する」という流れで理解すると十分です。</p>

</div>
</div>
<div id="faq-question-1777656782205" class="rank-math-list-item">
<h3 class="rank-math-question "><span id="toc45">ヒストグラムのbinsとpd.cut()のbinsは同じですか？</span></h3>
<div class="rank-math-answer ">

<p>考え方は近いですが、目的が違います。<br />ヒストグラムの<code>bins</code>は分布をグラフで見るためのものです。<code>pd.cut()</code>の<code>bins</code>は、区間カテゴリを新しい列として作るためのものです。</p>

</div>
</div>
</div>
</div><p>&lt;p&gt;The post <a rel="nofollow" href="https://pythondatalab.com/pandas-cut/">pandas cut()の使い方｜bins・labelsで数値を区間分けする方法を解説</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-cut/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
