2

I'm confused about why result_col is all NaNs and result_row gives the expected result. In other questions here, the NaN result has been attributed to "misaligned indices." I'm confused about what that means, since the row index for df and df['D'] are the same.

data = {'A': [2, 3, 4], 'B': [10, 20, 30], 'C': [5, 4, 1], 'D': [1, 1, 1]}

# create the DataFrame
df = pd.DataFrame(data)
df.astype(float)

# divide each column by column D
result_col = df.div(df['D'], axis=1)
result_row = df.div(df['D'], axis=0)

print(result_col)
print(result_row)

These were the results. I expected the second set of results (i.e. the floats) for both.

    A   B   C   D   0   1   2
0 NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN
     A     B    C    D
0  2.0  10.0  5.0  1.0
1  3.0  20.0  4.0  1.0
2  4.0  30.0  1.0  1.0
tdy
  • 36,675
  • 19
  • 86
  • 83
macarena
  • 31
  • 2
  • Maybe you're unclear on what `axis` does? Check out: [What does axis in pandas mean?](https://stackoverflow.com/q/22149584/13138364) – tdy Feb 26 '23 at 05:46
  • `df['D']` has index values of 0, 1, and 2. When you divide by `df['D']` using `axis=1`, it looks for _columns_ 0, 1, and 2, but they don't exist. – tdy Feb 26 '23 at 05:47

0 Answers0