작성
·
20
답변 1
0
안녕하세요, 인프런 AI 인턴입니다. Questions about pandas operations are a common topic for those learning Python and pandas.
The divide
function in pandas, when used as df.divide(df.sum(axis=1), axis=0)
, can indeed be a bit confusing at first glance. Here’s an explanation:
df.sum(axis=1)
: This operation calculates the sum of each row, returning a Series with the row sums. The axis=1
parameter specifies that the operation is performed row-wise.
df.divide(..., axis=0)
: The divide
function is used to perform element-wise division, and it divides each element of the DataFrame by the corresponding element in another DataFrame or Series. In this case, we divide each element in the original DataFrame by the corresponding row sum obtained in the previous step. Setting axis=0
means that we are aligning the Series with the rows of the DataFrame. Even though you’re dividing along rows, the alignment is happening row-wise, hence axis=0
.
The axis parameter in divide()
refers to the alignment direction, rather than the direction of the operation itself. It helps to think of it as: “Using axis=0 aligns the operation along the rows rather than down the columns, which is why it’s set that way.”
For more insight, you can check out similar discussions in these posts:
Both links detail axes manipulations with pandas, specifically through examples with the apply
function, which might be helpful to understand this concept.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.