VALUEERROR

Python ValueError の直し方|invalid literal for int() などを逆引き

invalid literal for int() with base 10: ''・too many values to unpack など、表示された英語から原因と直し方を引けます。

🎯 対象: ValueError で止まった初心者 ⏱️ 読了: 約9分 🧪 実測: Windows 11・Python 3.15.2/3.14.7/3.12.10・2026-11-28

結論:ValueError は「型は合っているが、値の中身が使えない」ときに出ます。最終行のコロンの後ろに出る値を、まず見てください。invalid literal for int() with base 10: '' なら、渡したのは空の文字列です。

1. 結論:エラー文別の早見表

エラー文主な原因直し方
invalid literal for int() with base 10・could not convert string to float空文字・小数・カンマ・単位入り文字を取り除く・try
cannot convert float NaN to integer・Exceeds the limit (4300 digits)NaN・桁数の上限math.isnan()・上限を上げる
too many values to unpack・not enough values to unpack左の変数と右の要素の数が違う*rest・len()・.items()
x not in list・3 is not in list・substring not found無い値を remove()・index()in で先に確かめる
time data ... does not match format・unconverted data remains日付の書式違い・時刻が余る書式を文字列に合わせる
day is out of range for month・day 30 must be in range存在しない日付月末日を先に求める
math domain error・expected a nonnegative inputsqrt() に負の数・log(0)渡す前に if
max() iterable argument is empty・empty range in randint空のリスト・引数の大小が逆default=・小さいほうを先に
JSONDecodeError・StatisticsErrorValueError の子の例外except ValueError でも捕まる
The truth value of a Series is ambiguouspandas・NumPy を if・and に使った.any()・& と括弧

型が合わないときの TypeError とは別の例外です。短い入門はPython エラー辞典の ValueError にあります。

🧪
検証環境(2026年11月28日実測)

Windows 11 Pro・Python 3.15.2・3.14.7・3.12.10。2026年11月28日時点の最新は 3.15.2 と 3.14.10 で、3.14 系は 3.14.7 で試しました。pandas 3.1.1・NumPy 2.5.5 は 3.14.7 だけです。表の文は標準エラーの最終行です。

2. 3.14 で文が変わった6つ(新旧の対応表)

検索で見た英語と手元の表示が違っても、原因は同じことがあります。次の6つは 3.12.10 だけ古い文でした。

コード3.15.2・3.14.73.12.10
a, b = [1, 2, 3]too many values to unpack (expected 2, got 3)too many values to unpack (expected 2)
[1, 2].index(3)list.index(x): x not in list3 is not in list
date(2026, 2, 30)day 30 must be in range 1..28 for month 2 in year 2026day is out of range for month
math.sqrt(-1)expected a nonnegative input, got -1.0math domain error
math.log(0)expected a positive input
random.randint(5, 1)empty range in randint(5, 1)empty range in randrange(5, 2)

CPython の変更履歴とソースの比較では、どれも 3.14.0 からです。unpack は gh-122239、list.index は gh-121288、日付は gh-70647、randint は gh-131435 で入りました。math は gh-101410 で、What's New 3.14 の math の節にも載っています。3.13 は試していませんが、3.13 のソースは古い文のままでした。

3. invalid literal for int()・could not convert string to float の直し方

int()・float() に数字として読めない文字列を渡しています。次は3版とも同じ結果でした。

コード結果
int('abc')・int('')・int('3.14')・int('1,000')・int('100円')invalid literal for int() with base 10: 'abc'(後ろの値は渡したもの)
float('abc')・float('')・float('1,000.5')could not convert string to float: 'abc'(同上)
int(' 12 \n')(前後に空白と改行)エラーなし・12
int('12')(全角数字)エラーなし・12

前後の空白と全角数字は int() が受け付けます(公式ドキュメント)。空白より、カンマ・小数点・単位を疑ってください。

s = " 1,000 "
print(int(s.strip().replace(",", "")))   # 1000(カンマは replace が要る)
print(int(float("3.14")))                # 3(小数点以下は切り捨て)

'' は入力欄が空か、CSV の空のセルです(分け方は10章)。入力欄の値で float() が通すもの・弾くものは BMI 計算アプリの一覧にあります。

cannot convert float NaN to integer・Exceeds the limit (4300 digits)

コード最終行(3版同じ)
int(float('nan'))cannot convert float NaN to integer
int('9' * 5000)Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits; use sys.set_int_max_str_digits() to increase the limit

NaN は欠損値で、整数にできません。math.isnan(v) が True になる値は先に外します。

4300桁の上限は、巨大な数字で処理を止める攻撃への対策です(公式の説明)。sys.set_int_max_str_digits(6000) の後は5000桁も変換できました(3版で実行)。上げるのは信頼できるデータだけにします。

4. too many values to unpack・not enough values to unpack の直し方

左に並べた変数の数と、右の要素の数が合っていません。

コード最終行
a, b = [1, 2, 3]版で違う(2章)
a, b, c = [1, 2]not enough values to unpack (expected 3, got 2)
name, age = 'taro'.split(',')not enough values to unpack (expected 2, got 1)
a, b = 'abc'too many values to unpack (expected 2)
for k, v in {'apple': 100}:too many values to unpack (expected 2)
for k, v in {'ab': 100}:エラーなし・a b と表示

辞書をそのまま for で回すと、キーの文字列を分けようとします。'apple' は5文字なので失敗しました。キーが 'ab' の2文字だと黙って通り、k に 'a'、v に 'b' が入ります。

3.14 から付く got 3 は、リスト・タプル・辞書を = で直接分けたときだけでした。文字列と辞書のキーは 3.15.2 でも付きません。

a, *rest = [1, 2, 3]
print(a, rest)                               # 1 [2, 3](残りをまとめて受ける)

parts = "taro".split(",")
if len(parts) == 2:
    name, age = parts
else:
    print("2つに分けられない:", parts)         # 2つに分けられない: ['taro']

name, age = "taro,12,x".split(",", 1)
print(name, age)                             # taro 12,x(最初のカンマだけで分ける)

for k, v in {"apple": 100}.items():
    print(k, v)                              # apple 100

CSV を split(",") で分けると、空行や列の足りない行で got 1 になります。辞書の読み方は KeyError の直し方にあります。

5. x not in list・substring not found の直し方

コード最終行
[1, 2].remove(3)list.remove(x): x not in list(3版同じ)
[1, 2].index(3)版で違う(2章)
'abc'.index('z')substring not found(3版同じ)

無い値を消す・探すと出ます。3.14 からの list.index() の文には探した値が出ないので、print() で確かめます。

lst = [1, 2]
if 3 in lst:
    lst.remove(3)
print(lst)   # [1, 2](無ければ何もしない)

辞書や集合で無いキーを使うと KeyError で、似ている例外の比較にまとめています。

6. 日付:does not match format・unconverted data remains の直し方

コード最終行
datetime.strptime('2026/11/28', '%Y-%m-%d')time data '2026/11/28' does not match format '%Y-%m-%d'
datetime.strptime('2026-11-28 10:00', '%Y-%m-%d')unconverted data remains: 10:00
datetime.fromisoformat('2026/11/28')Invalid isoformat string: '2026/11/28'
date(2026, 2, 30)版で違う(2章)

unconverted data remains は、書式で読んだ後に文字が余ったという意味です。コロンの後ろの空白2つのうち1つは、余った ' 10:00' の先頭です。

from datetime import datetime, date
import calendar

print(datetime.strptime("2026/11/28", "%Y/%m/%d"))         # 2026-11-28 00:00:00
print(datetime.strptime("2026-11-28 10:00", "%Y-%m-%d %H:%M"))  # 2026-11-28 10:00:00
print(calendar.monthrange(2026, 2)[1])                     # 28(2026年2月の末日)
print(date.fromisoformat("2026-11-28"))                    # 2026-11-28

書式コードの一覧は日付フォーマット早見表の strptime、月末の扱いは月末日の求め方です。

7. math domain error・max() が空・randint などの直し方

コード最終行直し方
math.sqrt(-1)・math.log(0)版で違う(2章)渡す前に if
max([])・min([])max() iterable argument is empty(min は min())default=
random.randint(5, 1)版で違う(2章)小さいほうを先に
range(0, 10, 0)range() arg 3 must not be zerostep を 0 以外に

2章に無い行は3版とも同じ文でした。

import math, random

x = -1
print(math.sqrt(x) if x >= 0 else "負の数なので計算しない")
print(max([], default=None))             # None
print(random.randint(1, 5) in range(1, 6))   # True

詳しい文になったのは math の一部の関数です。それ以外は 3.14 でも math domain error のままだとソースで確かめました。math.log(0.0) と float を渡すと、3.15.2・3.14.7 は got 0.0 まで出ました。

8. except ValueError で捕まる子の例外

名前が ValueError でなくても、ValueError の子なら except ValueError で捕まります。

コード最終行
json.loads('')json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
json.loads("{'a': 1}")... Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
statistics.mean([])statistics.StatisticsError: mean requires at least one data point
pd.Series([1, None]).astype(int)pandas.errors.IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer. ...

親子の関係は json・statistics の公式ドキュメントと pandas 3.1.1 のソースで確かめました(下は3版で実行)。

import json, statistics

for f in (lambda: json.loads(""), lambda: statistics.mean([])):
    try:
        f()
    except ValueError as e:
        print(type(e).__name__)   # JSONDecodeError → StatisticsError の順に表示

ファイルを読むときの UnicodeDecodeError も子で、except ValueError で捕まりました(3版で実行)。

9. pandas・NumPy:The truth value of a Series is ambiguous など

3.14.7 での最終行です(ValueError: は省略)。

コード最終行
if pd.Series([1, 2]) > 1:・(条件) and (条件)The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().
if np.array([1, 2]) > 1:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
pd.DataFrame({'a': [1, 2], 'b': [1]})All arrays must be of the same length
pd.to_numeric(pd.Series(['1', 'x']))Unable to parse string 'x' at position 1
pd.to_datetime(['2026-11-28', 'abc'])time data "abc" doesn't match format "%Y-%m-%d". You might want to try:(続きに3行の案内)
int の列と文字列の列で mergeYou are trying to merge on int64 and str columns for key 'k'. ...(astype(int) で型をそろえると通った)
np.arange(6).reshape(4, 2)cannot reshape array of size 6 into shape (4,2)

値が複数ある Series は、if で真偽を決められません。「どれか」なら .any()、「全部」なら .all() です(pandas の説明)。条件は and でなく & でつなぎ、それぞれ括弧で囲みます(条件の結合)。

a = np.array([1, 2])
print((a > 1).any(), (a > 1).all())          # True False

df = pd.DataFrame({"a": [1, 5], "b": [2, 6]})
print(df[(df["a"] > 1) & (df["b"] > 1)].to_dict("list"))  # {'a': [5], 'b': [6]}

print(pd.to_numeric(pd.Series(["1", "x"]), errors="coerce").tolist())  # [1.0, nan]
print(pd.to_datetime(pd.Series(["2026-11-28", "abc"]), errors="coerce").tolist())
# [Timestamp('2026-11-28 00:00:00'), NaT]
print(pd.Series([1, None]).astype("Int64").tolist())  # [1, <NA>]
print(np.arange(6).reshape(-1, 2).shape)   # (3, 2)(-1 は残りから決まる)

pd・np を import した後の断片です(3.14.7 だけで実行)。errors="coerce" は読めない値を NaN・NaT に変えるので、変わった件数を後で確かめます。"Int64" は欠損を持てる整数型です。実データの例は証券会社 CSV の読み込みです。

10. try/except の書き方:ValueError だけを捕まえる

入力やファイルの値は、変換してみて失敗したら分けます。

def to_int(text):
    try:
        return int(text)
    except ValueError:
        return None

print(to_int("12"), to_int("abc"), to_int(""))   # 12 None None

except: だけで書くと、関係ない間違いまで隠れます。未定義の変数 txt で int(txt) を書くと、except: は NameError まで捕まえて 0 のまま進みました。except ValueError: なら NameError で止まります(3版で実行)。

'-5' は isdecimal() が False なので、負の数を受けるなら try が向いています。他の例外はエラー辞典の逆引き表で引けます。

11. よくある質問(FAQ)

Q. invalid literal for int() with base 10: '' はどういう意味ですか?

空の文字列を int() に渡したという意味です。入力欄が空のまま、CSV の空のセルなどで出ます。空かどうかを先に確かめるか、try で分けます(3章・10章)。

Q. 検索すると math domain error と出てきますが、手元では違う文です。

3.14 から文が変わりました。math.sqrt(-1) は 3.12.10 で math domain error、3.14.7・3.15.2 で expected a nonnegative input, got -1.0 です。python -V で版を確かめ、2章で引いてください。

Q. 全角の数字を int() に渡すとエラーになりますか?

なりませんでした。int('12') は3版とも 12 です。isdecimal() も通るので isascii() で弾きます。

本記事は、生成AIを活用して下書きし、運営者が内容を確認・編集したうえで公開しています。AIの利用方針は免責事項をご覧ください。

12. まとめ

  • コロンの後ろの値を見る。'' なら空文字、'1,000' ならカンマ
  • unpack は左右の数をそろえる。辞書は .items() で回す
  • pandas の条件は & と括弧、if には .any()・.all()

直ったら次はこちら。

📌
参考にした一次情報と検証環境(2026年11月28日実測)

ValueError・int()・整数文字列の桁数制限・json・statistics(Python 公式)、What's New 3.14、CPython の変更(2章)、pandas 3.1.1 のドキュメントとソース。実測環境は1章のとおりです。