I have a DataFrame that looks like this:
JavaScript
x
13
13
1
AD1 AD2 AD3 AD4 AD5
2
1 0 0 0 0 0
3
2 0 0 0 0 0
4
3 0 0 0 0 0
5
4 0 0 0 0 0
6
5 0 0 0 0 0
7
..
8
497 138099424 126282256 0 197637664 0
9
498 90184696 53508360 90254688 66803036 57421672
10
499 41476688 54889712 36677268 33858400 50282272
11
500 26322476 27609302 26245020 20566374 23664970
12
501 595136256 241994400 489766144 314901408 730741120
13
I need to find the mean of each row, ignoring instances of 0. My initial plan was to replace 0 with NaN and then get the mean excluding NaN.
I tried to replace 0
with NaN
, however this didn’t work, and the DataFrame still contained 0. I tried:
JavaScript
1
3
1
df = df.replace(0, np.nan)
2
df = df.replace(0, np.nan, inplace=True)
3
The second issue is when I tried to calculate the mean, even knowing 0
would be included, the mean could not be calculated. I used:
JavaScript
1
2
1
df = df.assign(mean=df.mean(axis=1))
2
The outcome was:
JavaScript
1
13
13
1
AD1 AD2 AD3 AD4 AD5 mean
2
1 0 0 0 0 0 NaN
3
2 0 0 0 0 0 NaN
4
3 0 0 0 0 0 NaN
5
4 0 0 0 0 0 NaN
6
5 0 0 0 0 0 NaN
7
..
8
497 138099424 126282256 0 197637664 0 NaN
9
498 90184696 53508360 90254688 66803036 57421672 NaN
10
499 41476688 54889712 36677268 33858400 50282272 NaN
11
500 26322476 27609302 26245020 20566374 23664970 NaN
12
501 595136256 241994400 489766144 314901408 730741120 NaN
13
How can I accomplish this?
Advertisement
Answer
I tried to replace 0 with NaN, however this didn’t work, and the DataFrame still contained 0. I tried:
Convert your string values to numeric
JavaScript
1
16
16
1
df['mean'] = df.astype(float).replace(0, np.nan).mean(axis=1)
2
print(df)
3
4
# Output
5
AD1 AD2 AD3 AD4 AD5 mean
6
1 0 0 0 0 0 NaN
7
2 0 0 0 0 0 NaN
8
3 0 0 0 0 0 NaN
9
4 0 0 0 0 0 NaN
10
5 0 0 0 0 0 NaN
11
497 138099424 126282256 0 197637664 0 154006448.0
12
498 90184696 53508360 90254688 66803036 57421672 71634490.4
13
499 41476688 54889712 36677268 33858400 50282272 43436868.0
14
500 26322476 27609302 26245020 20566374 23664970 24881628.4
15
501 595136256 241994400 489766144 314901408 730741120 474507865.6
16