将CSV记录转换为tensor。 每列映射到一tensor。
语法:
tf.io.decode_csv(
records, record_defaults, field_delim=',', use_quote_delim=True, na_value='',
select_cols=None, name=None
)
常用参数:
records
: string类型的tensor, 每个字符串都是csv中的一个记录/行,所有记录都应该具有相同的格式。
record_defaults
:具有特定类型的Tensor对象列表。可接受的类型是float32,float64,int32,int64,string。
field_delim
: 一个可选的字符串,默认为“,”,分隔记录中字段的字符分隔符。
返回:
tensor对象的列表。 具有与record_defaults相同的类型。 每个tensor将具有与记录相同的shape。
异常:
ValueError
: 如果任何参数格式不正确。
示例:
作用是解析csv文件,接下来举例说明如何使用decode_csv来把一个由“,”分隔的csv字符串解析成各个值的。
1、
sample_str = '1,2,3,4,5'
record_defaults = [tf.constant(0, dtype=tf.int32)] * 5
parsed_fields = tf.io.decode_csv(sample_str, record_defaults)
print(parsed_fields)
[<tf.Tensor: id=24, shape=(), dtype=int32, numpy=1>, <tf.Tensor: id=25, shape=(), dtype=int32, numpy=2>, <tf.Tensor: id=26, shape=(), dtype=int32, numpy=3>, <tf.Tensor: id=27, shape=(), dtype=int32, numpy=4>, <tf.Tensor: id=28, shape=(), dtype=int32, numpy=5>]
2、
sample_str = '1,2,3,4,5'
record_defaults = [
tf.constant(0, dtype=tf.int32),
0,
np.nan,
"hello",
tf.constant([])
]
parsed_fields = tf.io.decode_csv(sample_str, record_defaults)
print(parsed_fields)
[<tf.Tensor: id=35, shape=(), dtype=int32, numpy=1>, <tf.Tensor: id=36, shape=(), dtype=int32, numpy=2>, <tf.Tensor: id=37, shape=(), dtype=float32, numpy=3.0>, <tf.Tensor: id=38, shape=(), dtype=string, numpy=b'4'>, <tf.Tensor: id=39, shape=(), dtype=float32, numpy=5.0>]
3、给空值
record_defaults = [
tf.constant(0, dtype=tf.int32),
0,
np.nan,
"hello",
tf.constant([])
]
try:
parsed_fields = tf.io.decode_csv(',,,,', record_defaults)
except tf.errors.InvalidArgumentError as ex:
print(ex)
Field 4 is required but missing in record 0! [Op:DecodeCSV]
4、给出相对于record_defaults更多的fields
record_defaults = [
tf.constant(0, dtype=tf.int32),
0,
np.nan,
"hello",
tf.constant([])
]
try:
parsed_fields = tf.io.decode_csv('1,2,3,4,5,6,7', record_defaults)
except tf.errors.InvalidArgumentError as ex:
print(ex)
Expect 5 fields but have 7 in record 0 [Op:DecodeCSV]