【问题标题】:csv to pandas.df to numpy to prepare data for tensorflowcsv 到 pandas.df 到 numpy 为 tensorflow 准备数据
【发布时间】:2021-10-25 02:28:13
【问题描述】:

您好,可能需要一些帮助..

刚开始使用 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字符串. 定义形状也有点复杂。 有没有简单的方法来构建它?

【问题讨论】:

    标签: python pandas numpy tensorflow


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这似乎有效!图像的大小会是这样的......? data = np.array(data).reshape((eol_lines[0],len(eol_lines), 5)) 只需要统计一行中的元素!?
    • 似乎正是您所需要的!下次发布问题时,尽量确保问题的所有维度(例如 EOL 块数和每个块的行数)都不同,以免数量之间出现混淆。
    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2016-12-09
    • 2022-12-09
    • 1970-01-01
    相关资源
    最近更新 更多