python - 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 中一行中的值是我的“图像”中一个位置的数据集。让我们称之为“RGBXY”。所以第一行是“图像”中的左上角像素。下一个 csv 行是“图像”中的下一个“像素”,依此类推......直到#EOL。从这里是“图像”中的蝾螈行。上面的例子是一个 (3x3x5) 数组
目标是在 3D 数组中构建它。我试图抓住一个 df = pd.read_csv("") 但这会给我的数组提供奇怪的类型(对象),我无法在最后使用它。我猜是因为#EOL字符串. 定义形状也有点复杂。有没有一种简单的方法来构建它?
解决方案
您应该将 .csv 视为常规 .json,以从其余行中区分出哪些行是 #EOL。然后,只需检索一个长字符串中的数据,将其拆分,将其转换为浮点数并使用带有 .reshape 的 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 块的行数,因为老实说,我不完全理解您将如何定义图像的大小。
推荐阅读
- android - Android中ROTATION VECTOR的实现
- python - Python 的请求模块返回代理错误
- amazon-web-services - S3 传输加速语义
- python - 绘制曲面除以值的 3d 数据
- python - 对两个数组的每个元素求和
- python - Python对数颜色图/调色板
- primeng - 防止在 p-tree PrimeNG 中拖放后删除节点
- javascript - 如何在 vue.js 中将弹出悬停状态更改为活动状态(单击时)
- python-3.x - Extract a table out of data frame in pandas based on a condition
- powershell - -f 空白空间的未知原因