it-source

비단뱀 판다의 기둥 이름에서 기둥 색인 가져오기

criticalcode 2022. 11. 1. 00:01
반응형

비단뱀 판다의 기둥 이름에서 기둥 색인 가져오기

R에서는 열 이름을 기준으로 열 인덱스를 검색해야 하는 경우 다음을 수행할 수 있습니다.

idx <- which(names(my_data)==my_colum_name)

팬더 데이터 프레임에서도 같은 작업을 수행할 수 있는 방법이 있습니까?

네, 이용하실 수 있습니다..get_loc():

In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)

In [47]: df.columns.get_loc("pear")
Out[47]: 2

솔직히 말해서 나 자신도 이런 게 별로 필요 없긴 하지만.보통 이름으로 접근하면 원하는 대로 됩니다( )df["pear"],df[["apple", "orange"]], 또는 아마도df.columns.isin(["orange", "pear"])인덱스 번호를 원하는 경우는 확실히 있습니다만.

다음은 목록 이해를 통한 해결책입니다.cols는 인덱스를 가져올 열의 목록입니다.

[df.columns.get_loc(c) for c in cols if c in df]

DSM의 솔루션은 동작합니다만, 다음과 같이 직접 대응하고 싶은 경우는,which할 수 있다(df.columns == name).nonzero()

일치하는 열을 여러 개 찾는 경우 방법을 사용하여 벡터화된 솔루션을 사용할 수 있습니다.그 때문에,df데이터 프레임 및query_cols검색할 열 이름으로서 구현은 다음과 같습니다.

def column_index(df, query_cols):
    cols = df.columns.values
    sidx = np.argsort(cols)
    return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]

샘플 실행 -

In [162]: df
Out[162]: 
   apple  banana  pear  orange  peach
0      8       3     4       4      2
1      4       4     3       0      1
2      1       2     6       8      1

In [163]: column_index(df, ['peach', 'banana', 'apple'])
Out[163]: array([4, 1, 0])

열 위치에서 열 이름을 원하는 경우(OP 질문의 반대쪽) 다음을 사용할 수 있습니다.

>>> df.columns.get_values()[location]

@DSM 사용 예:

>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

>>> df.columns

Index(['apple', 'orange', 'pear'], dtype='object')

>>> df.columns.get_values()[1]

'orange'

기타 방법:

df.iloc[:,1].name

df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.) 

여러 개의 열 인덱스를 반환할 경우pandas.Indexmethod (일치 라벨이 있는 경우):

df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)

인덱스에 고유하지 않은 라벨이 있는 경우(컬럼은 고유 라벨만 지원합니다).와 같은 작업이 필요합니다.get_indeder:

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]}, 
    index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)

두 방법 모두 공차가 있는 가장 가까운 값을 갖는 부동 값에 대해 f.i.를 사용한 부정확한 인덱싱을 지원합니다.두 개의 인덱스가 지정된 라벨과의 거리가 같거나 중복된 경우 인덱스 값이 더 큰 인덱스가 선택됩니다.

df = pd.DataFrame(
    {"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
    index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)

DSM의 답변을 약간 수정하려면get_loc에는 현재 버전의 Panda(1.1.5)에 있는 인덱스 유형에 따라 몇 가지 이상한 속성이 있으므로 인덱스 유형에 따라 인덱스, 마스크 또는 슬라이스를 다시 얻을 수 있습니다.한 변수의 인덱스를 추출하기 위해 전체 열을 수정하고 싶지 않기 때문에 다소 답답합니다.훨씬 더 간단한 방법은 기능을 완전히 피하는 것입니다.

list(df.columns).index('pear')

매우 직설적이고 아마 꽤 빠를 것이다.

이거 어때:

df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
out = np.argwhere(df.columns.isin(['apple', 'orange'])).ravel()
print(out)
[1 2]

열이 존재할 수도 있고 존재하지 않을 수도 있는 경우 다음(위의 변수)이 작동합니다.

ix = 'none'
try:
     ix = list(df.columns).index('Col_X')
except ValueError as e:
     ix = None  
     pass

if ix is None:
   # do something
import random
def char_range(c1, c2):                      # question 7001144
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)      
df = pd.DataFrame()
for c in char_range('a', 'z'):               
    df[f'{c}'] = random.sample(range(10), 3) # Random Data
rearranged = random.sample(range(26), 26)    # Random Order
df = df.iloc[:, rearranged]
print(df.iloc[:,:15])                        # 15 Col View         

for col in df.columns:             # List of indices and columns
    print(str(df.columns.get_loc(col)) + '\t' + col)

![결과] (결과)

언급URL : https://stackoverflow.com/questions/13021654/get-column-index-from-column-name-in-python-pandas

반응형