【问题标题】:length of array and string don't match when converting them back and forth来回转换时数组和字符串的长度不匹配
【发布时间】:2017-04-17 11:58:47
【问题描述】:

我正在处理一个 csv 文件,该文件在一列中包含图像(矢量化)。这里是the csv file ~240MB

我正在尝试将 Image 字符串转换为整数列表,重塑为矩阵,翻转,并将其重塑回列表,然后最终转换回长字符串。但事情并没有如我所愿。以下是我的代码:

import pandas as pd
import numpy as np
df = pd.read_csv('training.csv')
img = df['Image'][0] # take the first row as example
img_int = np.fromstring(img, sep=' ')  # img_int.shape --> (9216,), good.
img_matrix = img_int.reshape(96,96)
img_matrix_flipped = np.fliplr(img_matrix) # img_matrix_flipped.shape --> (96,96), good
img_matrix_flipped_vector = img_matrix_flipped.reshape(1, 9216) # img_matrix_flipped_vector.shape --> (1, 9216), good
img_matrix_flipped_vector_str = str(img_matrix_flipped_vector) # len(img_matrix_flipped_vector_str) --> 44, NOT GOOD!!!

我很困惑为什么 len(img_matrix_flipped_vector_str) 是 44。字符串不应该包含所有 9216 整数吗?请帮忙!

【问题讨论】:

  • 据我所知,您的代码没有任何问题。最好在数组上使用 tostring() 方法,而不是获取所有数组符号和换行符。

标签: python string pandas numpy multidimensional-array


【解决方案1】:

我刚刚发现: 数组上的string() 方法返回可打印的字符串表示。如果你打印这个字符串,你会看到数字,中间可能会被缩短为“...”。 要将 numpy 数组转换为字符串,请在数组上使用 tostring()tobytes() 方法。 您还可能希望将形状重塑为一维数组而不是二维数组,其中一个轴的大小为 1 (array.reshape(9216) 而不是 array.reshape(1,9216)),这取决于您的目标。

【讨论】:

  • 嗨@Dschoni,你是对的,str() 方法是罪魁祸首!但是tostring()tobytes() 也没有给我我想要的……
  • 我在使用tostring()tobytes()时得到了一堆\x000\x0000
【解决方案2】:

根据@Dschoni 的回答,我认为我不应该使用str() 方法。然后找到another topic,帮我找到了解决办法:

img_matrix_flipped_vector = img_matrix_flipped.reshape(9216)
list = img_matrix_filpped_vector.tolist()
str_I_want = ' '.join([str(i) for i in list])

【讨论】:

  • 只是补充一点:您可以直接遍历扁平数组以节省内存,而不是迭代列表。根据你调用 join 方法的字符串,这将是分隔符。
猜你喜欢
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 2016-06-10
相关资源
最近更新 更多