猿问

如何将列表合并到嵌套列表?

我有一个列表(虹膜数据样本),我想缩放变量(除了最后一列)。我做了一个循环来做到这一点,但我不知道如何在这个过程之后合并它们。


X = [[5.1, 3.5, 1.4, 0.2, 0.0],

     [4.9, 3.0, 1.4, 0.2, 0.0],

     [4.7, 3.2, 1.3, 0.2, 0.0],

     [4.6, 3.1, 1.5, 0.2, 0.0],

     [5.0, 3.6, 1.4, 0.2, 0.0],

     [5.4, 3.9, 1.7, 0.4, 0.0]]

我试图做一个循环来缩放,但我不知道如何合并。


我试过了:


from statistics import mean, stdev

for i in range(len(X)):

    valores = []

    for j in range(len(X[i])-1):

        z = []

        coluna = [item[j] for item in X]

        media = mean(coluna)

        desv = stdev(coluna)

        z = [round(((x - media) / desv), 4) for x in coluna]

        valores = valores + z

valores = valores + [valor[-1] for valor in X]

我的实际结果是:


valores = [0.5207,-0.1736,-0.8678,-1.2149,0.1736,1.562,0.3401,-1.1175,-0.5345,-0.826,0.6316,1.5062,-0.3627,-0.3627,-1.0882,0.3627,-0.3627,1.8137,-0.4082,-0.4082,-0.4082,-0.4082,-0.4082,2.0412,0.0,0.0,0.0,0.0,0.0,0.0]

但我想得到:


valores = [[0.5207, 0.3401, -0.3627, -0.4082, 0.0],

           [-0.1736, -1.1175, -0.3627, -0.4082, 0.0],

           [-0.8678, -0.5345, -1.0882, -0.4082, 0.0],

           [-1.2149, -0.826, 0.3627, -0.4082, 0.0],

           [0.1736, 0.6316, -0.3627, -0.4082, 0.0],

           [1.562, 1.5062, 1.8137, 2.0412, 0.0]]


GCT1015
浏览 187回答 2
2回答

慕田峪4524236

使用熊猫:数据:X = [[5.1, 3.5, 1.4, 0.2, 0.0],     [4.9, 3.0, 1.4, 0.2, 0.0],     [4.7, 3.2, 1.3, 0.2, 0.0],     [4.6, 3.1, 1.5, 0.2, 0.0],     [5.0, 3.6, 1.4, 0.2, 0.0],     [5.4, 3.9, 1.7, 0.4, 0.0]]代码:编写函数def valores以产生所需的转换创建一个数据框X应用于valores数据框中的相应列import pandas as pddef valores(x):    return [round(((y - x.mean()) / x.std()), 4) for y in x]df = pd.DataFrame(X)df[[0, 1, 2, 3]] = df[[0, 1, 2, 3]].apply(lambda x: valores(x))输出:      0       1       2       3    4 0.5207  0.3401 -0.3627 -0.4082  0.0-0.1736 -1.1175 -0.3627 -0.4082  0.0-0.8678 -0.5345 -1.0882 -0.4082  0.0-1.2149 -0.8260  0.3627 -0.4082  0.0 0.1736  0.6316 -0.3627 -0.4082  0.0 1.5620  1.5062  1.8137  2.0412  0.0

翻阅古今

不优雅:out = []for i in range(1+len(valores)//len(X)):    aux = []    for j in range(len(X[0])):        aux.append(valores[i+len(X)*j])    out.append(aux)print(out)[[0.5207, 0.3401, -0.3627, -0.4082, 0.0], [-0.1736, -1.1175, -0.3627, -0.4082, 0.0], [-0.8678, -0.5345, -1.0882, -0.4082, 0.0], [-1.2149, -0.826, 0.3627, -0.4082, 0.0], [0.1736, 0.6316, -0.3627, -0.4082, 0.0], [1.562, 1.5062, 1.8137, 2.0412, 0.0]]
随时随地看视频慕课网APP

相关分类

Python
我要回答