pandas 熊猫从 csv 读取数据帧,索引为字符串,而不是 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31813500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:43:57  来源:igfitidea点击:

Pandas read dataframe from csv with index as string, not int

pythonnumpypandas

提问by Quentin

My csv file is as following :

我的 csv 文件如下:

INDEX, VAL
04016170,22
04206261,11
0420677,11

df = pd.read_csv('data.csv', index_col='INDEX')

df = pd.read_csv('data.csv', index_col='INDEX')

How can I force pandas to read the index as string and not as integer (to preserve the first 0) ?

如何强制Pandas将索引读取为字符串而不是整数(以保留第一个0)?

回答by EdChum

You can pass the dtypeas a param this will map the column to the passed dtype:

您可以将dtype作为参数传递,这会将列映射到传递的数据类型:

In [130]:
import io
import pandas as pd
t="""INDEX,VAL
04016170,22
04206261,11
0420677,11"""
df = pd.read_csv(io.StringIO(t), index_col='VAL', dtype={'INDEX':str})
df

Out[130]:
        INDEX
VAL          
22   04016170
11   04206261
11    0420677

In [131]:    
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 22 to 11
Data columns (total 1 columns):
INDEX    3 non-null object
dtypes: object(1)
memory usage: 48.0+ bytes

EDIT

编辑

OK, you can do it this way, there is a bug here when you explicitly set the index_colin read_csv, so you have to load the csv in first and then call set_indexafter loading:

好的,你可以这样做,当你显式设置index_colin 时read_csv,这里有一个错误,所以你必须先加载 csv ,然后set_index在加载后调用:

In [134]:
df = pd.read_csv(io.StringIO(t), dtype={'INDEX':str})
df = df.set_index('INDEX')
df

Out[134]:
          VAL
INDEX        
04016170   22
04206261   11
0420677    11

回答by themachinist

Another solution in two lines:

两行的另一种解决方案:

df = pd.read_csv('data.csv',index_col=0)
df.index = [str(x) for x in df.index]

or

或者

df.index = df.index.astype(str)