DataFrame에 750x750 행렬이 있다고 가정합니다.
df=
c1 c2 c3 ... c750
c1 5 2 5 ... 3
c2 3 1 5 ... 80
c3 4 2 7 ... 10
. . . . ... .
. . . . ... .
. . . . ... .
c750 8 3 5 ... 1
각 행에 대해 4 개의 가장 높은 값을 포함하는 열을 찾고 싶습니다. 다음과 같이 쉽게 할 수 있습니다.
a = df.values
a.sort(axis=1)
sorted_table = a[:,-4::]
b = a[:,::-1]
그러나 내가 얻은 결과는 인덱스와 열 이름이없는 목록입니다.
[[ 98. 29. 15. 10.]
[ 93. 91. 75. 60.]
[ 48. 21. 17. 10.]
.
.
.
...]
정렬 된 값이 참조하는 열 이름을 알고 싶다면 어떻게해야합니까?
표시하고 싶습니다 :
df=
c1 c512 c20 c57 c310
c2 c317 c133 c584 c80
c3 c499 c289 c703 c100
. . . . ... .
. . . . ... .
. . . . ... .
c750 c89 c31 c546 c107
어디
c512 is referring to 98
c20 is referring to 29
c57 is referring to 15
and so and so.
이것이 최선의 답변이라고 생각하지 않지만 작동한다고 생각합니다. 나는 for
pandas에서 루프를 사용하는 것을 싫어 하지만 그것을 수행하는 pandas 방법을 생각할 수 없었습니다.
import pandas as pd
import numpy as np
#array_size = 10
#--- Generate Data and create toy Dataframe ---
array_size = 750
np.random.seed(1)
data = np.random.randint(0, 1000000, array_size**2)
data = data.reshape((array_size, array_size))
df = pd.DataFrame(data, columns=['c'+str(i) for i in range(1, (array_size)+1)])
df.index = df.columns
#--- Transpose the dataframe to more familiarly sort by columns instead of rows ---
df = df.T
#--- Rank values in dataframe using max method where highest value is rank 1 ---
df = df.rank(method='max', ascending=False)
#--- Create empty dataframe to put data into ---
new_df = pd.DataFrame()
#--- For loop for each column to get top ranks less than 5, sort them, reset index, drop i column
for i in df.columns:
s = df[i][df[i] < 5].sort_values().reset_index().drop(i, axis=1)
new_df = pd.concat([new_df, s.T])
#--- The new_df index will say 'index', this reassigns the transposed column names to new_df's index
new_df.index = df.columns
print(new_df)
출력 :
0 1 2 3
c1 c479 c545 c614 c220
c2 c249 c535 c231 c680
c3 c657 c603 c137 c740
c4 c674 c424 c426 c127
... ... ... ... ...
c747 c251 c536 c321 c296
c748 c55 c383 c437 c103
c749 c138 c495 c299 c295
c750 c178 c556 c491 c445
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다