# -*- coding: utf-8 -*-
'''
about numpy.genfromtxt, means generate from txt file
https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html
numpy.genfromtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0,
converters=None, missing_values=None, filling_values=None, usecols=None, names=None,
excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True,
defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None,
encoding='bytes')
See also
numpy.loadtxt equivalent function when no data is missing.
'''
from cryptography.hazmat.primitives.serialization import Encoding
# ndarray_fromtxt_lt = numpy.loadtxt('data.txt',delimiter=',',dtype=numpy.str)
# # ndarray_fromtxt_lt = numpy.loadtxt(open('data.txt','r',encoding='utf-8'),delimiter=',',dtype=numpy.str)
# # ndarray_fromtxt_lt = numpy.loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)
# print(type(ndarray_fromtxt_lt))
# print(ndarray_fromtxt_lt)
# ndarray_data = numpy.genfromtxt(fname='data.txt', dtype=str,delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows)
# file = open('data.txt',encoding='utf-8')
'''
-使用场景:数据转换 (编码转换、值转换)
-关键参数:converters
The set of functions that convert the data of a column to a value.
The converters can also be used to provide a default value for missing data: converters = {3: lambda s: float(s or 0)}.
-它是函数的集合,可以编写函数(或者使用lambda)对某列的值进行转换,常用的场景有:编码转换、值转换等
-特别注意!!!
- 1、转换函数的输入,默认都是bytes类型,跟encoding参数有关,跟dtype参数无关。
- dtype影响数据的最终呈现形式
- encoding影响数据处理过程
- 关于encoding参数的官方说明:
- Override this value to receive unicode arrays and pass strings as input to converters.
- If set to None the system default is used. The default value is ‘bytes’.
- 2、转换函数的返回的类型,必须跟设置的dtype保持一致,否则会造成不可预料的数据丢失。
- 例如,genfromtxt设置dtype=str,即所有列的类型都是str,那么,转换函数的返回类型也必须是str
- 3、如果数据中含有中文,可能会跟Windows系统默认的ascii字符集冲突,需要转码为utf-8
'''
import os
os.remove('data.txt')
fo = open('data.txt','a',encoding='utf-8')
fo.write("001,张三,man,24\n")
fo.write("002,李四,man,24\n")
fo.close()
import numpy
def convUTF8(x):
return x.decode('utf-8')
def convAdd(x):
return str(x,encoding='utf-8') + '+'
'''正确示范:单列处理'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str,
converters={1: convUTF8})
print(ndarry_1)
# [['001' '张三' 'man' '24']
# ['002' '李四' 'man' '24']]
'''正确示范:多列处理'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str,
converters={1: convUTF8,
2: lambda x: x.decode('utf-8') })
print(ndarry_1)
# [['001' '张三' 'man' '24']
# ['002' '李四' 'man' '24']]
'''错误示范:因为转换函数的返回类型没有跟输入类型保持一致,会造成数据丢失'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str,
converters={1: lambda x: 1})
print(ndarry_1)
# [('', 1, '', '') ('', 1, '', '')]
'''错误示范:对于一个列,只能一个转换函数,且只能处理一次,设置多次,是无效的'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str,
converters={1: convUTF8,
0: convAdd,
0: convAdd})
print(ndarry_1)
# [['001+' '张三' 'man' '24']
# ['002+' '李四' 'man' '24']]
'''
-使用场景:设置列的格式
-关键参数:dtype
- Data type of the resulting array.
- If None, the dtypes will be determined by the contents of each column, individually.
- 作为ndarray中的元素,dtype可以设置数据类型
'''
os.remove('data.txt')
fo = open('data.txt','a',encoding='utf-8')
fo.write("001,zhangsan,man,24\n")
fo.write("002,lisi,man,24\n")
fo.close()
'''错误示范:dtype=None,自动格式,但是差强人意。对于非数字的列,默认是bytes'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=None)
print(ndarry_1)
# [(1, b'zhangsan', b'man', 24) (2, b'lisi', b'man', 24)]
'''正确示范:全部列设置统一的数据类型。对于不含有中文的数据,dtype=str是可以的,如果含有中文,除了设置dtype=str以外,还要用converters做转码'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str)
print(ndarry_1)
# [['001' 'zhangsan' 'man' '24']
# ['002' 'lisi' 'man' '24']]
'''正确示范:逐列设置数据类型。需要另外了解dtype的种类。'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=[('c0','<i8'),('c1','<U32'),('c2','|S3'),('c3','f4')])
print(ndarry_1)
# [(1, 'zhangsan', b'man', 24.0) (2, 'lisi', b'man', 24.0)]
'''
-使用场景:数据切片
-关键参数:dtype
- Data type of the resulting array.
- If None, the dtypes will be determined by the contents of each column, individually.
- 作为ndarray中的元素,dtype可以设置数据类型
'''
'''
-使用场景:缺省值的处理
-关键参数:dtype
- Data type of the resulting array.
- If None, the dtypes will be determined by the contents of each column, individually.
- 作为ndarray中的元素,dtype可以设置数据类型
'''
'''
-使用场景:数据切片
-关键参数:skip_header
- 起始行
-关键参数:max_rows
- 最大行数
-关键参数:usecols
- 保留列
-关键参数:comments (执行顺序是最后的,先做行列切片,再做删除注释行)
- 注释符号。
- 如果是行首注释,正行都会被舍弃;
- 如果是行中其他位置的注释,会报错,以为改行被保留下来了,但是注释符号后面的字段丢失了。
'''
os.remove('data.txt')
fo = open('data.txt','a',encoding='utf-8')
fo.write("001,zhangsan,man,24\n")
fo.write("002,lisi,man,24\n")
fo.write("#003,wangwu,man,24\n")
fo.write("004,chenhua,wom,18\n")
fo.close()
'''正确示范:注意执行顺,先做行列切片,再做删除注释行'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=str,
skip_header=1,max_rows=3,
usecols=[0,2],
comments='#',
)
print(ndarry_1)
# [['002' 'man']
# ['004' 'wom']]
'''
-使用场景:填补缺失值(当dtype=None时,填补缺失值这个功能较好用,当dtype=str时,这个功能不生效,要再摸索)
-关键参数:missing_values
- 标记为缺失
-关键参数:filling_values
- 对缺失的位置进行填补
'''
os.remove('data.txt')
fo = open('data.txt','a',encoding='utf-8')
fo.write("10,11,,13\n")
fo.write("10,21,22,23\n")
fo.write("10,31,32,33\n")
fo.close()
'''正确示范:某列的缺失进行具体设置(其他列是默认缺失),全部列统一默认填补'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=None,
missing_values={0:10},
filling_values=999
)
print(ndarry_1)
# [[999 11 999 13]
# [999 21 22 23]
# [999 31 32 33]]
'''正确示范:某列的缺失,某列的填补'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=None,
missing_values={0:10},
filling_values={0:777,2:999}
)
print(ndarry_1)
# [[777 11 999 13]
# [777 21 22 23]
# [777 31 32 33]]
'''正确示范:所有列的缺失进行统一设置(但是默认缺失还是生效了)'''
ndarry_1 = numpy.genfromtxt(fname='data.txt',delimiter=',',dtype=None,
missing_values=10,
filling_values={0:777,2:999}
)
print(ndarry_1)
# [[777 11 999 13]
# [777 21 22 23]
# [777 31 32 33]]