CSV到pandas.Df到numpy为tensorflow准备数据



我可能需要一些帮助。

刚刚开始学习Python和编程,如果这是真正的初学者问题,那么很抱歉。

我有以下内容:从这样的csv文件开始…

1,2,3,4,5
2,5,6,8,9
4,7,6,8,7
#EOL
2,3,4,5,7
5,6,8,9,1
4,7,8,8,7
#EOL
2,3,4,5,7
5,6,8,9,1
4,7,8,8,7
#EOL

我需要这些值进入一个3D数组与TensorFlow玩一点。我纠结于以下几点。把它看作一个"图像"。在哪里CSV中一行中的值是我的"图像"中一个位置的数据集。我们就叫它"rgbx"吧。第一行是图像的左上角像素。下一个csv行是下一个像素。在"图像"中等等......直到终点。从这里开始,它是"图像"中的蝾螈行。上面的例子是一个(3x3x5)数组

目标是在3D数组中构建它。我试图抓住一个df = pd.read_csv("),但这会给我奇怪的类型(对象)我的数组,我不知怎么地不能在最后使用。我猜是因为#EOL字符串。另外,定义形状也有点复杂。有没有简单的方法来做这个?

您应该将.csv视为常规的.json,以便从其他行中区分出哪些行是#EOL。然后,只需检索长字符串中的数据,将其拆分,将其转换为float,并在您想要的数据形状中使用带有.重塑的numpy数组。

可以这样做:

import numpy as np
data = [] # Where we'll keep the data
eol_lines = [] # Where we'll store the number of lines in an #EOL block
# Open the .csv file
with open(csv_path) as file:
accumulator = 0
for line in file.readlines():
# Remove the eventual spaces and line returns
line = line.replace(' ', '').replace('n', '')
# Only keep non #EOL lines
if line != '#EOL':
data.append(line)
accumulator += 1
# Keep track of the #EOL block's number of line
else:
eol_lines.append(accumulator)
accumulator = 0
# Turn the data in a long string
data = ','.join(data)
# Turn the data in a long array
data = data.split(',')
# Turn strings in floats
data = [float(x) for x in data]
# Reshape the data
data = np.array(data).reshape((3, 3, 5))

这也计算了每个#EOL块的行数,因为,老实说,我不完全理解你将如何定义你的图像的大小。

最新更新