Multiply Two Pandas Series Produces NaN Entries Due to Indexes

Viewed 258

Multiply two series may result NaN values if they have unmatched indexes. I realized that and solved the issue by resetting the index.

Is this the best way of doing this? I wonder what is the best practice of doing this?

print(x)
3    2
4    2
5    2
6    2
7    2
8    6
9    2
Name: Count, dtype: int64

print(w)
0    0.035714
1    0.071429
2    0.107143
3    0.142857
4    0.178571
5    0.214286
6    0.250000
dtype: float64

Note that x and w have different indexes. Result is NaN where the indexes do not match.

x * w

0         NaN
1         NaN
2         NaN
3    0.285714
4    0.357143
5    0.428571
6    0.500000
7         NaN
8         NaN
9         NaN
dtype: float64

reset index then multiply

x.reset_index(drop=True) * w.reset_index(drop=True)
0    0.071429
1    0.142857
2    0.214286
3    0.285714
4    0.357143
5    1.285714
6    0.500000
dtype: float64
1 Answers

Yes it is good solution.

If possible different not default indices in both Series:

x.reset_index(drop=True) * w.reset_index(drop=True)

Alternative is convert to numpy array, only necessary same length of x, w:

x.to_numpy() * w
Related