import numpy as np
import pandas as pd
with open('file.dat') as fp:
width = len(fp.readline().strip().split(','))
dtypes = {i: np.int8 for i in range(width)}
# update the last column's dtype
dtypes[width-1] = np.int32
# reset the read position of the file pointer
fp.seek(0)
df = pd.read_csv(fp, sep=',', engine='c', header=None,
na_filter=False, dtype=dtypes, low_memory=False)
dtype = dict(zip(range(4000),['int8' for _ in range(3999)] + ['int32']))
考虑到这是可行的:
import pandas as pd
import numpy as np
data = '''\
1,2,3
4,5,6'''
fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, dtype={0:'int8',1:'int8',2:'int32'}, header=None)
print(df.dtypes)
返回:
0 int8
1 int8
2 int32
dtype: object
从文档中:
dtype : Type name or dict of column -> type, default None
Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32}
Use str or object to preserve and not interpret dtype. If converters
are specified, they will be applied INSTEAD of dtype conversion.
由于没有标题,列名是它们出现的整数顺序,即第一列是
df[0]
。要以编程方式将最后一列设置为int32
,您可以读取文件的第一行以获取数据帧的宽度,然后构建一个整数类型字典,使用列数作为键如果您确定了数字,您可以像这样重新创建字典:
考虑到这是可行的:
返回:
从文档中:
相关问题 更多 >
编程相关推荐