sourcecode

각 행의 최대값이 있는 열 이름 찾기

copyscript 2023. 6. 18. 16:13
반응형

각 행의 최대값이 있는 열 이름 찾기

다음과 같은 데이터 프레임이 있습니다.

Communications and Search   Business    General Lifestyle
0   0.745763    0.050847    0.118644    0.084746
0   0.333333    0.000000    0.583333    0.083333
0   0.617021    0.042553    0.297872    0.042553
0   0.435897    0.000000    0.410256    0.153846
0   0.358974    0.076923    0.410256    0.153846

각 행에 대해 최대값이 있는 열 이름을 얻고 싶습니다.원하는 출력은 다음과 같습니다.

Communications and Search   Business    General Lifestyle  Max
0   0.745763    0.050847    0.118644    0.084746           Communications 
0   0.333333    0.000000    0.583333    0.083333           Business  
0   0.617021    0.042553    0.297872    0.042553           Communications 
0   0.435897    0.000000    0.410256    0.153846           Communications 
0   0.358974    0.076923    0.410256    0.153846           Business 

와 함께 사용할 수 있습니다.axis=1각 행에서 가장 큰 값을 가진 열 찾기:

>>> df.idxmax(axis=1)
0    Communications
1          Business
2    Communications
3    Communications
4          Business
dtype: object

새 열 '최대'를 생성하려면 다음을 사용합니다.df['Max'] = df.idxmax(axis=1).

각 열에서 최대값이 발생하는 행 인덱스를 찾으려면 다음을 사용합니다.df.idxmax()(또는 동등하게)df.idxmax(axis=0)).

그리고 열의 이름이 포함된 열을 최대값으로 생성하고 열의 하위 집합만 고려하려면 @ajcr의 답변을 변형하여 사용합니다.

df['Max'] = df[['Communications','Business']].idxmax(axis=1)

할 수 있습니다apply데이터 프레임에 저장 및argmax()을 통해 각 행의axis=1

In [144]: df.apply(lambda x: x.argmax(), axis=1)
Out[144]:
0    Communications
1          Business
2    Communications
3    Communications
4          Business
dtype: object

다음은 얼마나 느리는지 비교하기 위한 벤치마크입니다.apply방법은 ~입니다.idxmax()위해서len(df) ~ 20K

In [146]: %timeit df.apply(lambda x: x.argmax(), axis=1)
1 loops, best of 3: 479 ms per loop

In [147]: %timeit df.idxmax(axis=1)
10 loops, best of 3: 47.3 ms per loop

또 다른 해결책은 각 행의 최대값 위치에 플래그를 지정하고 해당 열 이름을 가져오는 것입니다.특히 이 솔루션은 여러 열에 일부 행의 최대값이 포함되어 있고 각 1행의 최대값을 사용하여 모든이름을 반환하려는 경우에 효과적입니다.

case1

코드:

# look for the max values in each row
mxs = df.eq(df.max(axis=1), axis=0)
# join the column names of the max values of each row into a single string
df['Max'] = mxs.dot(mxs.columns + ', ').str.rstrip(', ')

약간의 변화:여러 개의 열에 최대값이 포함된 경우 하나의 열을 랜덤하게 선택하려면 다음을 수행합니다.

코드:

mxs = df.eq(df.max(axis=1), axis=0)
df['Max'] = mxs.where(mxs).stack().groupby(level=0).sample(n=1).index.get_level_values(1)

다음 열을 선택하여 특정 열에 대해 이 작업을 수행할 수도 있습니다.

# for column names of max value of each row
cols = ['Communications', 'Search', 'Business']
mxs = df[cols].eq(df[cols].max(axis=1), axis=0)
df['max among cols'] = mxs.dot(mxs.columns + ', ').str.rstrip(', ')

1:idxmax(1)최대값이 여러 열에 대해 동일한 경우 최대값을 가진 첫 번째 열 이름만 반환합니다. 이는 사용 사례에 따라 바람직하지 않을 수 있습니다.이 솔루션은 일반화됩니다.idxmax(1)특히, 각 행에서 최대값이 고유할 경우, 이 값은idxmax(1)해결책

numpy argmax를 사용하는 것은 빠르게 진행되고 있습니다.3,744,965 행의 데이터 프레임에서 테스트를 해봤는데 103ms가 소요됩니다.

%timeit df.idxmax(axis=1)
7.67 s ± 28.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit df.columns[df.to_numpy().argmax(axis=1)]
103 ms ± 355 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

언급URL : https://stackoverflow.com/questions/29919306/find-the-column-name-which-has-the-maximum-value-for-each-row

반응형