[英]How to read index data as string with pandas.read_csv()?
我正在尝试将csv文件作为带有pandas的DataFrame读取,我想将索引行读为字符串。 但是,由于索引的行没有任何字符,因此pandas将此数据作为整数处理。 如何读作字符串?
这是我的csv文件和代码:
[sample.csv]
uid,f1,f2,f3
01,0.1,1,10
02,0.2,2,20
03,0.3,3,30
[code]
df = pd.read_csv('sample.csv', index_col="uid" dtype=float)
print df.index.values
结果:df.index是整数,而不是字符串:
>>> [1 2 3]
但我想把df.index作为字符串:
>>> ['01', '02', '03']
还有一个附加条件:其余的索引数据必须是数值,它们实际上太多了,我不能用特定的列名指出它们。
传递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 param在被视为索引**的cols上被忽略:
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()
然后,我们使用所需的dtypes生成列名称的dict:
index_col_name = cols[0]
dtypes = dict(zip(cols[1:], [float]* len(cols[1:])))
dtypes[index_col_name] = str
我们得到索引名称,假设它是第一个条目,然后从其余的cols创建一个dict并将float
指定为所需的dtype并添加指定类型为str
的索引col,然后可以将其作为dtype
param传递to read_csv
如果结果不是字符串,则必须将其转换为字符串。 尝试:
result = [str(i) for i in result]
或者在这种情况下:
print([str(i) for i in df.index.values])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.