python - 将 pandas 数据框列导入为字符串而不是 int

标签 python pandas casting type-conversion dtype

我想将以下 csv 作为字符串而不是 int64 导入。 Pandas read_csv 自动将其转换为 int64,但我需要此列作为字符串。

ID
00013007854817840016671868
00013007854817840016749251
00013007854817840016754630
00013007854817840016781876
00013007854817840017028824
00013007854817840017963235
00013007854817840018860166


df = read_csv('sample.csv')

df.ID
>>

0   -9223372036854775808
1   -9223372036854775808
2   -9223372036854775808
3   -9223372036854775808
4   -9223372036854775808
5   -9223372036854775808
6   -9223372036854775808
Name: ID

不幸的是,使用转换器会得到相同的结果。

df = read_csv('sample.csv', converters={'ID': str})
df.ID
>>

0   -9223372036854775808
1   -9223372036854775808
2   -9223372036854775808
3   -9223372036854775808
4   -9223372036854775808
5   -9223372036854775808
6   -9223372036854775808
Name: ID

最佳答案

只是想重申这将适用于 pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

我也在创建一个关于检测整数溢出的问题。

编辑:在此处查看分辨率:https://github.com/pydata/pandas/issues/2247

更新,因为它可以帮助他人:

要将所有列作为str,可以这样做(来自评论):

pd.read_csv('sample.csv', dtype = str)

要将大多数或选择性列作为str,可以这样做:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

关于python - 将 pandas 数据框列导入为字符串而不是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293810/

相关文章:

python - 同时运行多个python程序

python - Pandas 数据框列表部分字符串匹配python

python - 获取 pandas 数据框中一列中 n 个单词的前 n/2 个

python - SQL Server DATE 作为字符串检索到 pandas

c++ - 编译器切换到禁用 c 风格转换中的 const_cast 语义?

c++ - 类型转换和异常处理

python - 处理消歧错误?

python - 如何使用 pandas 绘图

python - 比较 GroupBy 中的值并计算匹配的行数

python - python 中的多重类型转换不好吗?