【问题标题】:Convert an arary of string encoded lists into a multidimensional array将字符串编码列表数组转换为多维数组
【发布时间】:2021-07-27 06:32:40
【问题描述】:

当我读取 CSV 文件时,我的数据采用 (1, 6000, 200) 形状,但我想要 (6000, 200, 6) 形状的数据。 Python中是否有任何可能的方法将这个字符串[-9.3145 0.631 1.2924 -0.2776 -0.2061 -0.2084]转换为第三维?

from glob import glob
import numpy as np
strain1 = glob("myfile.csv")
df = [pd.read_csv(f).values for f in strain1]
X_train = np.asarray(df)

【问题讨论】:

  • 欢迎来到 SO!您能否展示一个简单版本的 CSV 和实际/预期结果数组?
  • 顺便说一句,将列表称为数据框 (df) 令人困惑
  • 欢迎回到 SO!查看tour。请edit您的问题添加详细信息。当然有一些方法可以重塑数据,但你究竟想如何重塑它呢?提供minimal reproducible example 将有助于提供一些简短的示例输入、所需输出和实际输出。如果您想了解更多提示,请参阅How to Ask

标签: python arrays multidimensional-array


【解决方案1】:

我使用下面的代码生成了一些测试数据:

import numpy as np
test_data = np.array(["[{:0.4f} {:0.4f} {:0.4f} {:0.4f} {:0.4f} {:0.4f}]".format(*np.random.uniform(low=-10, high=10, size=(6,))) for k in range(100)]).reshape(1,20,5)

这有望产生与您的阵列中的类似的东西。为了方便起见,我使用了 20,5 的尺寸 6000,200

Numpy 在 char 模块中有一堆内置函数来帮助进行这种类型的处理,如 here 所示。

# Get rid of the (1,x,x) extra dimension 
data_squeezed = np.squeeze(test_data)
data_squeezed.shape
# Returns (20, 5)
# data_squeezed[0,0] = '[-0.3523 -8.3259 -1.2245 -4.8143 8.1495 7.3349]'

# strip the leading and trailing brackets []
data_stripped = np.char.strip(data_squeezed, '[]')
# data_stripped[0,0] = '-0.3523 -8.3259 -1.2245 -4.8143 8.1495 7.3349'

# split the string into parts
data_split = np.char.split(data_stripped, ' ')
# data_split[0,0] = ['-0.3523', '-8.3259', '-1.2245', '-4.8143', '8.1495', '7.3349']

# convert the array of lists to an array
data_array_of_strings = np.array(data_split.tolist())
# data_array_of_strings[0,0] = array(['-0.3523', '-8.3259', '-1.2245', '-4.8143', '8.1495', '7.3349'], dtype='<U7')

# convert the string values to float values
data_array = data_array_of_strings.astype(float)
# data_array[0,0] = array([-0.3523, -8.3259, -1.2245, -4.8143,  8.1495,  7.3349])

# Or as a one liner
data_array = np.array(np.char.split(np.char.strip(np.squeeze(test_data), '[]'),' ').tolist()).astype(float)

# Check the shape 
data_array.shape
# Returns (20,5,6) as required

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 2012-11-17
    相关资源
    最近更新 更多