'How do I total sum of several columns based on argument python
I have been trying to get the total value of all columns based on an argument, but it didn't work out.
import numpy as np
np.random.seed(100)
NO= pd.DataFrame({'TR':'NO', 'A': np.random.randint(1, 10,3), 'B': np.random.randint(10, 20,3), 'C': np.random.randint(25, 35,3)})
YS= pd.DataFrame({'TR':'YS', 'A': np.random.randint(1, 10,3), 'B': np.random.randint(10, 20,3), 'C': np.random.randint(25, 35,3)})
frames = (NO, YS)
df = pd.concat(frames)
Total=df.loc[df['TR'] == 'NO', ['A', 'B', 'C']].sum()
The total would be a single value = 152
Solution 1:[1]
You have to sum twice to reduce the dimensional:
>>> df.loc[df['TR'] == 'NO', ['A', 'B', 'C']].sum().sum()
152
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 | Corralien |
