通过dtype参数指定dtype:
In [159]:
import pandas as pd
import io
t="""uid,f1,f2,f3
01,0.1,1,10
02,0.2,2,20
03,0.3,3,30"""
df = pd.read_csv(io.StringIO(t), dtype={'uid':str})
df.set_index('uid', inplace=True)
df.index
Out[159]:
Index(['01', '02', '03'], dtype='object', name='uid')
所以在你的情况下以下应该工作:
df = pd.read_csv('sample.csv', dtype={'uid':str})
df.set_index('uid', inplace=True)
单行等效项不起作用,因为此处仍然存在出色的pandas bug,其中将被视为索引的列上的 dtype 参数被忽略**:
df = pd.read_csv('sample.csv', dtype={'uid':str}, index_col='uid')
如果我们假设第一列是索引列,您可以动态执行此操作:
In [171]:
t="""uid,f1,f2,f3
01,0.1,1,10
02,0.2,2,20
03,0.3,3,30"""
cols = pd.read_csv(io.StringIO(t), nrows=1).columns.tolist()
index_col_name = cols[0]
dtypes = dict(zip(cols[1:], [float]* len(cols[1:])))
dtypes[index_col_name] = str
df = pd.read_csv(io.StringIO(t), dtype=dtypes)
df.set_index('uid', inplace=True)
df.info()
<class 'pandas.core.frame.DataFrame'>
Index: 3 entries, 01 to 03
Data columns (total 3 columns):
f1 3 non-null float64
f2 3 non-null float64
f3 3 non-null float64
dtypes: float64(3)
memory usage: 96.0+ bytes
In [172]:
df.index
Out[172]:
Index(['01', '02', '03'], dtype='object', name='uid')
这里我们只读取标题行来获取列名:
cols = pd.read_csv(io.StringIO(t), nrows=1).columns.tolist()
然后我们使用所需的数据类型生成列名的字典:
index_col_name = cols[0]
dtypes = dict(zip(cols[1:], [float]* len(cols[1:])))
dtypes[index_col_name] = str
我们得到索引名称,假设它是第一个条目,然后从其余列中创建一个 dict 并将 float 分配为所需的 dtype 并添加索引 col 指定类型为 str,您可以然后将此作为dtype 参数传递给read_csv