'Sum of column values in a string matrix using numpy in python
l=["101","111","011"] calculate sum of column values using numpy of string matrix for i in range(k): sum=0 for j in range(n): sum+=int(s[j][i])
Solution 1:[1]
The simplest would be:
>>> sum([int(x) for x in l])
223
If you want to use numpy:
a = np.array(l).astype(int)
>>> a
array([101, 111, 11])
>>> a.sum()
223
Solution 2:[2]
Assuming you want to sum per column/position
l=["101","111","011"]
[sum(map(int, x)) for x in zip(*l)]
#[2, 2, 3]
Not that this is different from a classical sum([int(x) for x in l]) if you reach a sum greater than 9:
l=["101","191","011"]
[sum(map(int, x)) for x in zip(*l)]
# [2, 10, 3]
sum([int(x) for x in l])
# 303
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pierre D |
| Solution 2 | mozway |
