0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pandas.read_csv: 数値に変換できない値が格納されているCSVを読み込むと、すべての値の型は文字列型である

Last updated at Posted at 2025-04-17

環境

  • Python 3.13.1
  • pandas 2.2.3

内容

以下のような、value列にいろんな種類の値が格納されているCSVを読み込みたいです。

bar.csv
key,value
count,1
name,alice

当然といえば当然なのですが、数値と数値以外が混在していると、すべての値は文字列型です。

In [52]: df=pandas.read_csv("bar.csv")

In [53]: df.dtypes
Out[53]:
key      object
value    object
dtype: object

In [54]: df["value"]
Out[54]:
0        1
1    alice
Name: value, dtype: object

In [55]: for v in df["value"]:
    ...:     print(f"{v=}, {type(v)=}")
    ...:
v='1', type(v)=<class 'str'>
v='alice', type(v)=<class 'str'>

数値に変換できる'1'は、数値型に変換されるものだと思い込んでいたので、少しハマりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?