programing

판다 데이터 프레임의 열 순서 설정

telecom 2023. 7. 29. 08:11
반응형

판다 데이터 프레임의 열 순서 설정

개인적인 선호도에 따라 판다 데이터 프레임의 열을 다시 정렬하는 방법이 있습니까(즉, 알파벳 또는 숫자로 정렬되지 않고 특정 규칙을 따르는 것과 더 유사함)?

간단한 예:

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

다음을 생성합니다.

   one thing other thing  second thing
0          1           a           0.1
1          2           e           0.2
2          3           i           1.0
3          4           o           2.0

대신에, 저는 이것을 원합니다.

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

이 경우에만 해당되는 솔루션이 아니라 일반 솔루션을 제공하십시오.감사합니다.)

열 이름을 입력하여 직접 주문을 선택하면 됩니다.이중 브래킷을 확인합니다.

frame = frame[['column I want first', 'column I want second'...etc.]]

다음을 사용할 수 있습니다.

columnsTitles = ['onething', 'secondthing', 'otherthing']

frame = frame.reindex(columns=columnsTitles)

여기 제가 자주 사용하는 해결책이 있습니다.대량의 열이 포함된 큰 데이터 집합이 있는 경우 모든 열을 수동으로 재정렬하지는 않을 것입니다.

자주 사용하는 처음 몇 개의 열만 순서대로 정렬하고 다른 모든 열은 순서대로 정렬할 수 있습니다.이것은 R에서 일반적인 접근 방식입니다.df %>%select(one, two, three, everything())

따라서 먼저 순서를 지정하고 목록의 다른 모든 열 앞에 배치할 열을 수동으로 입력할 수 있습니다.cols_to_order.

그런 다음 나머지 열을 결합하여 새 열에 대한 목록을 구성합니다.

new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())

이 후에는 다음을 사용할 수 있습니다.new_columns다른 해결책이 제시한 바와 같이.

import pandas as pd
frame = pd.DataFrame({
    'one thing': [1, 2, 3, 4],
    'other thing': ['a', 'e', 'i', 'o'],
    'more things': ['a', 'e', 'i', 'o'],
    'second thing': [0.1, 0.2, 1, 2],
})

cols_to_order = ['one thing', 'second thing']
new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())
frame = frame[new_columns]

   one thing  second thing other thing more things
0          1           0.1           a           a
1          2           0.2           e           e
2          3           1.0           i           i
3          4           2.0           o           o

당신은 또한 다음과 같은 것을 할 수 있습니다.df = df[['x', 'y', 'a', 'b']]

import pandas as pd
frame = pd.DataFrame({'one thing':[1,2,3,4],'second thing':[0.1,0.2,1,2],'other thing':['a','e','i','o']})
frame = frame[['second thing', 'other thing', 'one thing']]
print frame
   second thing other thing  one thing
0           0.1           a          1
1           0.2           e          2
2           1.0           i          3
3           2.0           o          4

또한 다음을 사용하여 열 목록을 가져올 수 있습니다.

cols = list(df.columns.values)

출력 결과는 다음과 같습니다.

['x', 'y', 'a', 'b']

그러면 수동으로 재정렬하기가 쉽습니다.

사전 대신 목록으로 구성

frame = pd.DataFrame([
        [1, .1, 'a'],
        [2, .2, 'e'],
        [3,  1, 'i'],
        [4,  4, 'o']
    ], columns=['one thing', 'second thing', 'other thing'])

frame

   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           4.0           o

OrderedDict를 사용할 수도 있습니다.

In [183]: from collections import OrderedDict

In [184]: data = OrderedDict()

In [185]: data['one thing'] = [1,2,3,4]

In [186]: data['second thing'] = [0.1,0.2,1,2]

In [187]: data['other thing'] = ['a','e','i','o']

In [188]: frame = pd.DataFrame(data)

In [189]: frame
Out[189]:
   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

'columns' 매개 변수를 추가합니다.

frame = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']},
        columns=['one thing', 'second thing', 'other thing']
)

인덱스를 사용해 보십시오. 따라서 인덱스 순서가 원하는 대로 되도록 일반 솔루션을 사용하십시오.

l=[0,2,1] # index order
frame=frame[[frame.columns[i] for i in l]]

이제:

print(frame)

대상:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

오래된 질문이지만 사용할 수도 있습니다.loc그리고.iloc:

frame = frame.loc[:, ['column I want first', 'column I want second', "other thing"]]

frame = frame.iloc[:, [1, 3, 2]]
df = df.reindex(columns=["A", "B", "C"])

저는 이것이 가장 간단하고 효과적이라고 생각합니다.

df = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

df = df[['one thing','second thing', 'other thing']]

언급URL : https://stackoverflow.com/questions/41968732/set-order-of-columns-in-pandas-dataframe

반응형