Programming

팬더에서 특정 열 이름 바꾸기

procodes 2020. 6. 13. 20:13
반응형

팬더에서 특정 열 이름 바꾸기


라는 데이터 프레임이 data있습니다. 열 헤더를 하나만 바꾸려면 어떻게해야합니까? 예를 들어, gdplog(gdp)?

data =
    y  gdp  cap
0   1    2    5
1   2    3    9
2   8    7    2
3   3    4    7
4   6    7    7
5   4    8    3
6   8    2    8
7   9    9   10
8   6    6    4
9  10   10    7

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

rename이의 PARAM로 DICT 받아들이는 쇼 columns당신은 단지 하나의 항목으로 DICT을 통과 할 수 있도록합니다.

관련 참조


list-comprehension단일 열의 이름을 변경해야하는 경우 훨씬 빠른 구현이 사용 됩니다.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

여러 열의 이름을 바꾸어야 할 경우 다음과 같은 조건식을 사용하십시오.

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

또는,를 사용하여 매핑을 구성 dictionary하고 수행 list-comprehension그것의에 get이전 이름으로 기본 값을 설정하여 운영 :

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key→old name, value→new name

df.columns = [col_dict.get(x, x) for x in df.columns]

타이밍 :

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

팬더에서 특정 열의 이름을 바꾸려면 어떻게합니까?

v0.24 이상에서 한 번에 하나 이상의 열 이름을 바꾸려면

한 번에 모든 열의 이름을 바꾸어야하는 경우

  • DataFrame.set_axis()와 방법 axis=1. 목록과 같은 순서를 전달하십시오. 전체 수정 옵션도 제공됩니다.

renameaxis=1

df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df

   y gdp cap
0  x   x   x
1  x   x   x
2  x   x   x
3  x   x   x
4  x   x   x

0.21+에서는 다음을 사용하여 axis매개 변수를 지정할 수 있습니다 rename.

df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')

   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

( rename기본적으로 제자리에 있지 않으므로 결과를 다시 할당 해야합니다 .)

이 기능은 나머지 API와의 일관성을 향상시키기 위해 추가되었습니다. 새로운 axis인수는 columns매개 변수와 유사 하며 동일한 작업을 수행합니다.

df.rename(columns={'gdp': 'log(gdp)'})

   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

rename 또한 각 열에 대해 한 번 호출되는 콜백을 허용합니다.

df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')

   y  g  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

이 특정 시나리오의 경우

df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)

Index.str.replace

Similar to replace method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace method for string and regex-based replacement.

df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df

   y log(gdp) cap
0  x        x   x
1  x        x   x
2  x        x   x
3  x        x   x
4  x        x   x

The advantage of this over the other methods is that str.replace supports regex (enabled by default). See the docs for more information.


Passing a list to set_axis with axis=1

Call set_axis with a list of header(s). The list must be equal in length to the columns/index size. set_axis mutates the original DataFrame by default, but you can specify inplace=False to return a modified copy.

df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)

  cap log(gdp)  y
0   x        x  x
1   x        x  x
2   x        x  x
3   x        x  x
4   x        x  x

Note: In future releases, inplace will default to True.

Method Chaining
Why choose set_axis when we already have an efficient way of assigning columns with df.columns = ...? As shown by Ted Petrou in [this answer],(https://stackoverflow.com/a/46912050/4909087) set_axis is useful when trying to chain methods.

Compare

# new for pandas 0.21+
df.some_method1()
  .some_method2()
  .set_axis()
  .some_method3()

Versus

# old way
df1 = df.some_method1()
        .some_method2()
df1.columns = columns
df1.some_method3()

The former is more natural and free flowing syntax.

참고URL : https://stackoverflow.com/questions/19758364/rename-specific-columns-in-pandas

반응형