your programing

팬더의 테이블 앞으로 이름으로 열 이동

lovepro 2023. 6. 11. 16:32
반응형

팬더의 테이블 앞으로 이름으로 열 이동

여기 내 df가 있습니다.

                             Net   Upper   Lower  Mid  Zsore
Answer option                                                
More than once a day          0%   0.22%  -0.12%   2    65 
Once a day                    0%   0.32%  -0.19%   3    45
Several times a week          2%   2.45%   1.10%   4    78
Once a week                   1%   1.63%  -0.40%   6    65

이름으로 열을 이동하는 방법("Mid") 표의 앞쪽, 색인 0.결과는 다음과 같습니다.

                             Mid   Upper   Lower  Net  Zsore
Answer option                                                
More than once a day          2   0.22%  -0.12%   0%    65 
Once a day                    3   0.32%  -0.19%   0%    45
Several times a week          4   2.45%   1.10%   2%    78
Once a week                   6   1.63%  -0.40%   1%    65

현재 코드는 다음을 사용하여 인덱스별로 열을 이동합니다.df.columns.tolist()이름으로 바꾸고 싶습니다.

우리는 사용할 수 있습니다.loc목록을 전달하여 순서를 변경합니다.

In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.loc[:, cols]
df
Out[28]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

또 다른 방법은 열에 대한 참조를 가져다가 전면에 다시 삽입하는 것입니다.

In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
df
Out[39]:
                      Mid Net  Upper   Lower  Zsore
Answer_option                                      
More_than_once_a_day    2  0%  0.22%  -0.12%     65
Once_a_day              3  0%  0.32%  -0.19%     45
Several_times_a_week    4  2%  2.45%   1.10%     78
Once_a_week             6  1%  1.63%  -0.40%     65

당신은, 매우 초기 버전의 판다들과 함께, 또한 사용할 수 있습니다.ix동일한 결과를 얻기 위해:

df = df.ix[:, cols]

그렇지만ixPanda 1.0 이후로 사용이 중단되었습니다.

제가 뭔가를 놓쳤을 수도 있지만, 이 대답들 중 많은 것들이 너무 복잡해 보입니다.단일 목록 내에서 열을 설정할 수 있어야 합니다.

전면 열:

df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]

또는 뒤로 이동하려는 경우:

df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]

두 개 이상의 열을 이동하려는 경우:

cols_to_move = ['Mid', 'Zsore']
df           = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]

이 솔루션을 선호합니다.

col = df.pop("Mid")
df.insert(0, col.name, col)

다른 제안된 답변보다 읽기 쉽고 빠릅니다.

def move_column_inplace(df, col, pos):
    col = df.pop(col)
    df.insert(pos, col.name, col)

성능 평가:

이 테스트의 경우 반복할 때마다 현재 마지막 열이 앞으로 이동됩니다.일반적으로 내부 방법이 더 잘 수행됩니다.도시 노먼의 해결책은 제자리에서 만들 수 있지만 에드첨의 방법은 다음과 같습니다..loc그리고 사친의 방법은 다음과 같습니다.reindex수 없다.

다른 방법들은 일반적이지만, 도시 노먼의 솔루션은 다음과 같이 제한됩니다.pos=0사이의 성능 차이는 관찰되지 않았습니다.df.loc[cols]그리고.df[cols]그래서 제가 다른 제안을 하지 않은 겁니다

원래 시스템(2019년): MacBook Pro(2015년 중반)에서 Python 3.6.8 및 팬더 0.24.2.
현재 시스템(2022):MacBook Pro(2021, Apple M1)에서 Python 3.10.5 및 팬더 1.4.3.

import numpy as np
import pandas as pd

n_cols = 11
df = pd.DataFrame(np.random.randn(200000, n_cols),
                  columns=range(n_cols))

def move_column_inplace(df, col, pos):
    col = df.pop(col)
    df.insert(pos, col.name, col)

def move_to_front_normanius_inplace(df, col):
    move_column_inplace(df, col, 0)
    return df

def move_to_front_chum(df, col):
    cols = list(df)
    cols.insert(0, cols.pop(cols.index(col)))
    return df.loc[:, cols]

def move_to_front_chum_inplace(df, col):
    col = df[col]
    df.drop(col.name, axis=1, inplace=True)
    df.insert(0, col.name, col)
    return df

def move_to_front_elpastor(df, col):
    cols = [col] + [ c for c in df.columns if c!=col ]
    return df[cols] # or df.loc[cols]

def move_to_front_sachinmm(df, col):
    cols = df.columns.tolist()
    cols.insert(0, cols.pop(cols.index(col)))
    df = df.reindex(columns=cols, copy=False)
    return df

def move_to_front_citynorman_inplace(df, col):
    # This approach exploits that reset_index() moves the index
    # at the first position of the data frame.
    df.set_index(col, inplace=True)
    df.reset_index(inplace=True)
    return df

def test(method, df):
    col = np.random.randint(0, n_cols)
    method(df, col)

col = np.random.randint(0, n_cols)
ret_mine = move_to_front_normanius_inplace(df.copy(), col)
ret_chum1 = move_to_front_chum(df.copy(), col)
ret_chum2 = move_to_front_chum_inplace(df.copy(), col)
ret_elpas = move_to_front_elpastor(df.copy(), col)
ret_sach = move_to_front_sachinmm(df.copy(), col)
ret_city = move_to_front_citynorman_inplace(df.copy(), col)

# Assert equivalence of solutions.
assert(ret_mine.equals(ret_chum1))
assert(ret_mine.equals(ret_chum2))
assert(ret_mine.equals(ret_elpas))
assert(ret_mine.equals(ret_sach))
assert(ret_mine.equals(ret_city))

결과:

# For n_cols = 11:
%timeit test(move_to_front_normanius_inplace, df)
# 137 µs ± 692 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 177 µs ± 10.7 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit test(move_to_front_sachinmm, df)
# 821 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
%timeit test(move_to_front_chum, df)
# 926 µs ± 10.7 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
%timeit test(move_to_front_elpastor, df)
# 901 µs ± 6.44 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 3.25 ms ± 32.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


# For n_cols = 31:
%timeit test(move_to_front_normanius_inplace, df)
# 188 µs ± 3.46 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit test(move_to_front_citynorman_inplace, df)
# 214 µs ± 649 ns per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
%timeit test(move_to_front_sachinmm, df)
# 5.17 ms ± 68.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum, df)
# 5.52 ms ± 82.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_elpastor, df)
# 5.48 ms ± 198 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit test(move_to_front_chum_inplace, df)
# 14.7 ms ± 317 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

위는 2022년 재방송에 대한 업데이트된 값입니다.도시 노먼의 솔루션과 나의 솔루션(노르마니우스)이 가장 큰 혜택을 받은 2~10개 요소별로 절대 수치가 감소했지만 지난 몇 년간 시스템별로 순위가 안정적으로 유지되었습니다.

판다에서 df.reindex() 함수를 사용할 수 있습니다. df is

                      Net  Upper   Lower  Mid  Zsore
Answer option                                      
More than once a day  0%  0.22%  -0.12%    2     65
Once a day            0%  0.32%  -0.19%    3     45
Several times a week  2%  2.45%   1.10%    4     78
Once a week           1%  1.63%  -0.40%    6     65

열 이름 목록 정의

cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']

원하는 위치로 열 이름 이동

cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']

그 다음에 사용df.reindex()재주문 기능

df = df.reindex(columns= cols)

출력: df

                      Mid  Upper   Lower Net  Zsore
Answer option                                      
More than once a day    2  0.22%  -0.12%  0%     65
Once a day              3  0.32%  -0.19%  0%     45
Several times a week    4  2.45%   1.10%  2%     78
Once a week             6  1.63%  -0.40%  1%     65

다른 솔루션의 다른 모든 열을 명시적으로 지정해야 하는 방식이 마음에 들지 않았습니다.

cfg_col_sel = ['Mid', 'Zscore']
cfg_col_sel = cfg_col_sel+[s for s in df.columns if not s in cfg_col_sel]
df = df[cfg_col_sel]

이는 또 다른 방법이지만 유연성이 떨어집니다.

df = df.set_index('Mid').reset_index()

다음은 열 위치를 재정렬하는 데 자주 사용하는 일반 코드 집합입니다.당신은 그것이 유용하다고 생각할지도 모릅니다.

cols = df.columns.tolist()
n = int(cols.index('Mid'))
cols = [cols[n]] + cols[:n] + cols[n+1:]
df = df[cols]

데이터 프레임의 행을 다시 정렬하려면 다음과 같은 목록을 사용합니다.

df = df[['Mid', 'Net', 'Upper', 'Lower', 'Zsore']]

이를 통해 나중에 코드를 읽을 때 수행된 작업이 매우 분명해집니다.또한 다음을 사용합니다.

df.columns
Out[1]: Index(['Net', 'Upper', 'Lower', 'Mid', 'Zsore'], dtype='object')

그런 다음 잘라내어 붙여넣어 다시 주문합니다.


열이 많은 데이터 프레임의 경우 열 목록을 변수에 저장하고 원하는 열을 목록 앞에 놓습니다.다음은 예입니다.

cols = [str(col_name) for col_name in range(1001)]
data = np.random.rand(10,1001)
df = pd.DataFrame(data=data, columns=cols)

mv_col = cols.pop(cols.index('77'))
df = df[[mv_col] + cols]

지금이다df.columns가지다.

Index(['77', '0', '1', '2', '3', '4', '5', '6', '7', '8',
       ...
       '991', '992', '993', '994', '995', '996', '997', '998', '999', '1000'],
      dtype='object', length=1001)
df.set_index('Mid').reset_index()

꽤 쉬운 방법인 것 같습니다.

열을 데이터 프레임 앞으로 이동하려면 를 사용할 수 있습니다.

df.set_index(df.pop('column_name'), inplace=True)
df.reset_index(inplace=True)

먼저 앞으로 가져올 열을 데이터 프레임의 인덱스로 설정해야 합니다.pop동작에서 하기 위해 하려면), 으로 를 호출합니다.reset_index()이전 인덱스를 데이터 프레임의 첫 번째 열로 만듭니다.


자세한 내용은 팬더의 데이터 프레임 열의 순서를 변경하는 방법을 참조하십시오.

여기 이것에 대한 아주 간단한 대답이 있습니다.

열 이름 주위에 있는 두 개의 (( ) '괄호'를 잊지 마십시오.그렇지 않으면 오류가 발생합니다.


# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

                             Mid   Upper   Lower  Net  Zsore
Answer option                                                
More than once a day          2   0.22%  -0.12%   0%    65 
Once a day                    3   0.32%  -0.19%   0%    45
Several times a week          4   2.45%   1.10%   2%    78
Once a week                   6   1.63%  -0.40%   1%    65

Python에서 열 이동 패키지를 사용하여 열을 이동할 수 있습니다.

pip install movecolumn

그런 다음 코드를 다음과 같이 작성할 수 있습니다.

import movecolumn as mc
mc.MoveTo1(df,'mid')

도움이 되길 바랍니다.

추신: 패키지는 여기에서 찾을 수 있습니다.https://pypi.org/project/movecolumn/

가장 간단한 방법은 다음과 같습니다.

df=df[[ 'Mid',   'Upper',   'Lower', 'Net'  , 'Zsore']]

쉽고 빠른 솔루션:

판다 >= 1.3(2022년 편집):

df.insert(0, 'mean', df.pop('mean'))

어때요 (판다의 경우 < 1.3, 원답)

df.insert(0, 'mean', df['mean'])

언급URL : https://stackoverflow.com/questions/25122099/move-column-by-name-to-front-of-table-in-pandas

반응형