Programing

Pandas Dataframe / Numpy Array "축"정의의 모호성

lottogame 2020. 10. 5. 07:31
반응형

Pandas Dataframe / Numpy Array "축"정의의 모호성


파이썬 축이 어떻게 정의되는지, 그리고 이들이 DataFrame의 행이나 열을 참조하는지에 대해 매우 혼란 스러웠습니다. 아래 코드를 고려하십시오.

>>> df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"])
>>> df
   col1  col2  col3  col4
0     1     1     1     1
1     2     2     2     2
2     3     3     3     3

따라서를 호출 df.mean(axis=1)하면 행에 걸쳐 평균을 얻을 수 있습니다.

>>> df.mean(axis=1)
0    1
1    2
2    3

그러나를 호출 df.drop(name, axis=1)하면 실제로 행이 아닌 column을 삭제합니다 .

>>> df.drop("col4", axis=1)
   col1  col2  col3
0     1     1     1
1     2     2     2
2     3     3     3

누군가가 pandas / numpy / scipy에서 "축"이 무엇을 의미하는지 이해하도록 도와 줄 수 있습니까?

참고로 DataFrame.mean잘못 정의되었을 수 있습니다. 것이 문서에 말한다 DataFrame.mean이가 axis=1열이 아닌 행에 걸쳐 평균을 뜻한다 ...


0 = down1 = across 로 기억하는 것이 가장 간단합니다 .

이것은 다음을 의미합니다.

  • axis=0각 열 아래 또는 행 레이블 (인덱스)에 메서드를 적용하는 데 사용 합니다.
  • axis=1각 행 또는 열 레이블에 방법을 적용하는 데 사용 합니다.

다음은 각 축이 참조하는 DataFrame의 부분을 보여주는 그림입니다.

Pandas는 NumPy의 단어 사용을 따른다는 것을 기억하는 것도 유용합니다 axis. 사용법은 NumPy의 용어집에 설명되어 있습니다 .

축은 차원이 두 개 이상인 배열에 대해 정의됩니다. 2 차원 배열에는 두 개의 해당 축이 있습니다. 첫 번째 축은 행을 가로 질러 수직 으로 아래로 이동하고 (축 0) 두 번째 축은 열을 가로 질러 가로로 이동합니다 (축 1) . [ 내 강조점 ]

따라서 질문의 방법과 관련하여는 df.mean(axis=1)올바르게 정의 된 것 같습니다. 열을 가로 질러 가로로 , 즉 각 개별 행을 따라 항목의 평균을 취합니다 . 반면에는 행에 걸쳐df.mean(axis=0) 수직 으로 아래쪽으로 작동하는 작업 입니다.

마찬가지로 df.drop(name, axis=1)가로 축을 직관적으로 가로 지르기 때문에 열 레이블에 대한 작업을 나타냅니다. 지정 axis=0하면 메서드가 대신 행에서 작동합니다.


설명하는 또 다른 방법 :

// Not realistic but ideal for understanding the axis parameter 
df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]],
                  columns=["idx1", "idx2", "idx3", "idx4"],
                  index=["idx1", "idx2", "idx3"]
                 )

---------------------------------------1
|          idx1  idx2  idx3  idx4
|    idx1     1     1     1     1
|    idx2     2     2     2     2
|    idx3     3     3     3     3
0

df.drop(축은 위치를 의미)

A: I wanna remove idx3.
B: **Which one**? // typing while waiting response: df.drop("idx3",
A: The one which is on axis 1
B: OK then it is >> df.drop("idx3", axis=1)

// Result
---------------------------------------1
|          idx1  idx2     idx4
|    idx1     1     1     1
|    idx2     2     2     2
|    idx3     3     3     3
0

df.apply(축은 방향을 의미)

A: I wanna apply sum.
B: Which direction? // typing while waiting response: df.apply(lambda x: x.sum(),
A: The one which is on *parallel to axis 0*
B: OK then it is >> df.apply(lambda x: x.sum(), axis=0)

// Result
idx1    6
idx2    6
idx3    6
idx4    6

이미 정답이 있지만 2 차원을 초과하는 또 다른 예를 들겠습니다.

파라미터 axis변경할 축을 의미 합니다.
예를 들어 차원이 axbxc 인 데이터 프레임이 있다고 가정 합니다.

  • df.mean(axis=1)차원이 ax 1 xc 인 데이터 프레임을 반환합니다 .
  • df.drop("col4", axis=1)차원이 ax (b-1) xc 인 데이터 프레임을 반환합니다 .

문자열 별칭 'index''columns' 를 정수 0/1 대신 사용할 수 있다는 것이 더 널리 알려져 있습니다. 별칭은 훨씬 더 명확하며 계산이 어떻게 수행되는지 기억하는 데 도움이됩니다. 'index'의 또 다른 별칭은 'rows' 입니다.

When axis='index' is used, then the calculations happen down the columns, which is confusing. But, I remember it as getting a result that is the same size as another row.

Let's get some data on the screen to see what I am talking about:

df = pd.DataFrame(np.random.rand(10, 4), columns=list('abcd'))
          a         b         c         d
0  0.990730  0.567822  0.318174  0.122410
1  0.144962  0.718574  0.580569  0.582278
2  0.477151  0.907692  0.186276  0.342724
3  0.561043  0.122771  0.206819  0.904330
4  0.427413  0.186807  0.870504  0.878632
5  0.795392  0.658958  0.666026  0.262191
6  0.831404  0.011082  0.299811  0.906880
7  0.749729  0.564900  0.181627  0.211961
8  0.528308  0.394107  0.734904  0.961356
9  0.120508  0.656848  0.055749  0.290897

When we want to take the mean of all the columns, we use axis='index' to get the following:

df.mean(axis='index')
a    0.562664
b    0.478956
c    0.410046
d    0.546366
dtype: float64

The same result would be gotten by:

df.mean() # default is axis=0
df.mean(axis=0)
df.mean(axis='rows')

To get use an operation left to right on the rows, use axis='columns'. I remember it by thinking that an additional column may be added to my DataFrame:

df.mean(axis='columns')
0    0.499784
1    0.506596
2    0.478461
3    0.448741
4    0.590839
5    0.595642
6    0.512294
7    0.427054
8    0.654669
9    0.281000
dtype: float64

The same result would be gotten by:

df.mean(axis=1)

Add a new row with axis=0/index/rows

Let's use these results to add additional rows or columns to complete the explanation. So, whenever using axis = 0/index/rows, its like getting a new row of the DataFrame. Let's add a row:

df.append(df.mean(axis='rows'), ignore_index=True)

           a         b         c         d
0   0.990730  0.567822  0.318174  0.122410
1   0.144962  0.718574  0.580569  0.582278
2   0.477151  0.907692  0.186276  0.342724
3   0.561043  0.122771  0.206819  0.904330
4   0.427413  0.186807  0.870504  0.878632
5   0.795392  0.658958  0.666026  0.262191
6   0.831404  0.011082  0.299811  0.906880
7   0.749729  0.564900  0.181627  0.211961
8   0.528308  0.394107  0.734904  0.961356
9   0.120508  0.656848  0.055749  0.290897
10  0.562664  0.478956  0.410046  0.546366

Add a new column with axis=1/columns

Similarly, when axis=1/columns it will create data that can be easily made into its own column:

df.assign(e=df.mean(axis='columns'))

          a         b         c         d         e
0  0.990730  0.567822  0.318174  0.122410  0.499784
1  0.144962  0.718574  0.580569  0.582278  0.506596
2  0.477151  0.907692  0.186276  0.342724  0.478461
3  0.561043  0.122771  0.206819  0.904330  0.448741
4  0.427413  0.186807  0.870504  0.878632  0.590839
5  0.795392  0.658958  0.666026  0.262191  0.595642
6  0.831404  0.011082  0.299811  0.906880  0.512294
7  0.749729  0.564900  0.181627  0.211961  0.427054
8  0.528308  0.394107  0.734904  0.961356  0.654669
9  0.120508  0.656848  0.055749  0.290897  0.281000

It appears that you can see all the aliases with the following private variables:

df._AXIS_ALIASES
{'rows': 0}

df._AXIS_NUMBERS
{'columns': 1, 'index': 0}

df._AXIS_NAMES
{0: 'index', 1: 'columns'}

When axis='rows' or axis=0, it means access elements in the direction of the rows, up to down. If applying sum along axis=0, it will give us totals of each column.

When axis='columns' or axis=1, it means access elements in the direction of the columns, left to right. If applying sum along axis=1, we will get totals of each row.

Still confusing! But the above makes it a bit easier for me.

참고URL : https://stackoverflow.com/questions/25773245/ambiguity-in-pandas-dataframe-numpy-array-axis-definition

반응형