2

I have a dataset of such form:

+--------+---+---------+--------+-------+-------+-------+
|            |  A      |  B     |   C   |   D   |   E   |
+------------+---------+--------+-------+-------+-------+
|      0     | 1       | 2      |   3   |   4   |   AB  |
+------------+---------+--------+-------+-------+-------+

I want to compute the mean value of the rows values between B to D. So for row 0 will be:

B+C+D/(3) = 3

How can I do that?

GGS
  • 153
  • 2
  • 11

2 Answers2

1

You can use .mean(axis=1) on the selected columns. Adding axis=1 means it will be applied on horizontal axis, or row-wise:

a = {'A':[1],'B':[2],'C':[3],'D':[4],'E':['AE']}
df = pd.DataFrame(a)
cols = ['B','C','D']
df['Average'] = df[cols].mean(axis=1)
print(df)

Output:

   A  B  C  D   E  Average
0  1  2  3  4  AE      3.0
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

You can use df.mean

df.loc[:, "b":"d"].mean(axis=1)

df = pd.DataFrame({"a": [1, 2], "b": [2, 3], "c": [3, 4], "d": [4, 5], "e": list("AB")})

df["s"] = df.loc[:, "b":"d"].mean(axis=1)

Outputs:

Out[12]:    a  b  c  d  e    s
         0  1  2  3  4  A  3.0
         1  2  3  4  5  B  4.0
Alex
  • 6,610
  • 3
  • 20
  • 38