yke*_*ke9 5 python csv indexing pandas
我正在尝试将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
Run Code Online (Sandbox Code Playgroud)
结果:df.index是整数,而不是字符串:
>>> [1 2 3]
Run Code Online (Sandbox Code Playgroud)
但我想把df.index作为字符串:
>>> ['01', '02', '03']
Run Code Online (Sandbox Code Playgroud)
还有一个附加条件:其余的索引数据必须是数值,它们实际上太多了,我不能用特定的列名指出它们.
传递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')
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,以下应该工作:
df = pd.read_csv('sample.csv', dtype={'uid':str})
df.set_index('uid', inplace=True)
Run Code Online (Sandbox Code Playgroud)
单行等价物不起作用,因为这里还有一个非常突出的pandas bug,其中dtype param在被视为索引**的cols上被忽略:
df = pd.read_csv('sample.csv', dtype={'uid':str}, index_col='uid')
Run Code Online (Sandbox Code Playgroud)
如果我们假设第一列是索引列,您可以动态执行此操作:
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')
Run Code Online (Sandbox Code Playgroud)
这里我们只读取标题行以获取列名:
cols = pd.read_csv(io.StringIO(t), nrows=1).columns.tolist()
Run Code Online (Sandbox Code Playgroud)
然后,我们使用所需的dtypes生成列名称的dict:
index_col_name = cols[0]
dtypes = dict(zip(cols[1:], [float]* len(cols[1:])))
dtypes[index_col_name] = str
Run Code Online (Sandbox Code Playgroud)
我们得到索引名称,假设它是第一个条目,然后从其余的cols创建一个dict并指定float
为所需的dtype并添加指定类型的索引col str
,然后你可以将它作为dtype
param 传递给read_csv
归档时间: |
|
查看次数: |
11974 次 |
最近记录: |