Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use numpy to calculate row mean in Python

Shulou Source: shulou.com Published: 2022-06-01 20:45:20 09月30日 Update

This article mainly explains "how to use numpy to find the row average in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to use numpy to find the row average in Python".

Title:

A two-dimensional array is randomly given, and the result returns the row mean.

Input requirements:

The first row: two integers separated by spaces, the first representing the row of matrix X (n) and the second representing the column of X (p).

The next n line: the value of the row in X.

Output requirements:

An array of numpy one-dimensional values, rounded to the second decimal.

Input sample: 2 2

1.5 1

22.9 output sample:

[1.25 2.45]

Ideas for solving the problem:

The simplest, most critical, and most important step is to import the numpy library.

Import numpy as np

You need to define the rows and columns of the numpy array, because you want to meet the randomness of the topic requirements, so instead of writing dead here, use input input. And the row and column must be of integer type, and the data type must be of int type. But the input value is a string, so you need to convert the input value.

N, p = [int (x) for x in input () .split ()]

Next, p values are entered for each row. I used a loop with a range of n, and each line could enter p values. Previously, you also need to define an empty array to facilitate the accumulation of subsequent arrays.

Arr = [] for i in range (n): arr + = [float (x) for x in input () .split ()]

The next step is to convert the array to an numpy array and reshape it into a two-dimensional array.

Arr = np.array (arr) .reshape (n, p)

Finally, you can directly use numpy's mean method to calculate the mean, but the topic requirement is to find the row mean, so you need to set up axis=1, calculate according to the column, and get the row mean. At the same time, the result needs to retain two decimal places, so you need to use the round method.

Arr.mean (axis=1) .round (2) complete code: import numpy as npn, p = [int (x) for x in input (). Split ()] arr = [] for i in range (n): arr + = [float (x) for x in input (). Split ()] arr = np.array (arr) .reshape (n, p) print (arr.mean (axis=1) .round (2)) so far, I believe you have a deeper understanding of "how to use numpy to find the line mean in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Array mean input next method type topic content decimal integer sample result row two-dimensional learning output practical deeper important rounded Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info MySQL MariaDB NVidia