問題描述
我想將以下 csv 作為字符串而不是 int64 導入.Pandas read_csv 自動將其轉換為 int64,但我需要此列作為字符串.
I would like to import the following csv as strings not as int64. Pandas read_csv automatically converts it to int64, but I need this column as string.
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
不幸的是,使用轉換器會得到相同的結果.
Unfortunately using converters gives the same result.
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:
Just want to reiterate this will work in 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
我也在創建一個關于檢測整數溢出的問題.
I'm creating an issue about detecting integer overflows also.
在此處查看解決方案:https://github.com/pydata/pandas/issues/2247
更新,因為它可以幫助他人:
Update as it helps others:
要將所有列作為str,可以這樣做(來自評論):
To have all columns as str, one can do this (from the comment):
pd.read_csv('sample.csv', dtype = str)
要將大多數或選擇性列作為str,可以這樣做:
To have most or selective columns as str, one can do this:
# 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)
這篇關于將 pandas 數據框列導入為字符串而不是 int的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!