创建一个仅包含元素数量(不包含列表)的随机(0〜5)numpy

时间:2018-10-02 09:41:15

标签: python-3.x

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/textInputEditText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:hint="Testing" />

    </android.support.design.widget.TextInputLayout>

</LinearLayout>

结果==> [4 2 0 5 2 1 2 0 0 5 5 4 3 4 5 5 0 5 3 1 3 4 3 2 2 5 5 2 1 1 0 1 3 1 5 4 4 0 4 3] < / p>

我想要。仅当0显示为“ nan”时,如何更改? 让我知道。我不了解Python。抱歉。

1 个答案:

答案 0 :(得分:0)

如果您想修改matrix以便用numpy.NaN值替换所有零-您不能这样做,因为np.NaN是浮点数,而matrix包含整数。您不能将它们混合在数组中。因此,您可以通过不同的方式获得接近您想要的东西。

您可以创建numpy array个浮点数:

def makeMatrix():
    matrix = np.random.randint(0, 5 + 1, 10).astype(float)
    matrix[matrix == 0] = np.NaN
    return matrix

print(makeMatrix())

输出:

[ 4.  2. nan  5.  2.  1.  2. nan nan  5.]

您可以创建整数和NaN值的list

def makeMatrix():
    matrix = np.random.randint(0, 5 + 1, 10)
    return matrix

matrix = makeMatrix()
matrix_to_display = list((val if val != 0 else np.NaN) for val in matrix)
print(matrix_to_display)

输出:

[4, 2, nan, 5, 2, 1, 2, nan, nan, 5]