首页 > 解决方案 > 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字符串. 定义形状也有点复杂。有没有一种简单的方法来构建它?

标签: pythonpandasnumpytensorflow

解决方案


您应该将 .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 块的行数,因为老实说,我不完全理解您将如何定义图像的大小。


推荐阅读