【问题标题】:Generate Python Array with one Column Fixed生成固定一列的 Python 数组
【发布时间】:2021-07-31 06:09:30
【问题描述】:

我正在尝试在 Python 中生成一个 5 列数组,其中每行中的第一个数字保持固定为 0.2,但每行中接下来的 4 个数字会有所不同,并且每行数字的总和为 1。所以类似于

[.2, .2, .2, .2, .2]
[.2, .3, .1, .2, .2]
[.2, .2,  0, .6,  0]
[.2, .5,  0, .1, .2]

这可能吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    如果您使用的是 NumPy,您可以使用 the normalization technique here 将 4 行的总和为 0.8,然后在开头添加一列 0.2。

    import numpy as np
    
    n = 0.2
    a = np.random.rand(4, 4)
    
    # Sum rows and divide by target
    s = a.sum(1) / (1-n)
    
    # Normalize rows
    normalized = a / s.reshape(-1, 1)
    print(normalized.sum(1))  # -> [0.8 0.8 0.8 0.8]
    
    # Add column of .2
    first_col = np.repeat(n, a.shape[0])
    final = np.concatenate((first_col.reshape(-1, 1), normalized), axis=1)
    print(final.sum(1))  # -> [1. 1. 1. 1.]
    

    示例值:

    >>> print(a)
    [[0.86134437 0.56626254 0.21527553 0.16657095]
     [0.01680889 0.4971182  0.61437178 0.77192482]
     [0.98655061 0.26207574 0.62670237 0.67427712]
     [0.83763804 0.41413746 0.16745744 0.02619564]]
    >>> print(s)
    [2.26181674 2.3752796  3.1870073  1.80678573]
    >>> print(normalized)
    [[0.3808197  0.25035739 0.09517815 0.07364476]
     [0.00707659 0.20928829 0.2586524  0.32498272]
     [0.30955392 0.08223255 0.1966429  0.21157062]
     [0.46360674 0.22921227 0.09268251 0.01449848]]
    >>> print(final)
    [[0.2        0.3808197  0.25035739 0.09517815 0.07364476]
     [0.2        0.00707659 0.20928829 0.2586524  0.32498272]
     [0.2        0.30955392 0.08223255 0.1966429  0.21157062]
     [0.2        0.46360674 0.22921227 0.09268251 0.01449848]]
    

    【讨论】:

    • 附言。我还在学习 NumPy,所以任何指针表示赞赏
    【解决方案2】:

    一个简单的答案是这样的:

    array = [0.2]
    rest = [ran.random() for i in range(4)]
    s = sum(rest)
    rest = [ i/s * 0.8 for i in rest ]
    array.extend(rest)
    

    【讨论】:

    • 第二行导致错误提示列表分配索引超出范围
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多