팬더에서 특정 열 이름 바꾸기
라는 데이터 프레임이 data
있습니다. 열 헤더를 하나만 바꾸려면 어떻게해야합니까? 예를 들어, gdp
에 log(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.rename()
withaxis=1
또는axis='columns'
(axis
논쟁은에서 소개되었습니다v0.21
.Index.str.replace()
문자열 / 정규식 기반 교체 용.
한 번에 모든 열의 이름을 바꾸어야하는 경우
DataFrame.set_axis()
와 방법axis=1
. 목록과 같은 순서를 전달하십시오. 전체 수정 옵션도 제공됩니다.
rename
와 axis=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
'Programming' 카테고리의 다른 글
timedelta를 총 초로 변환 (0) | 2020.06.13 |
---|---|
log4j vs 로그 백 (0) | 2020.06.13 |
Redis는 단일 스레드이며 동시 I / O는 어떻게 수행합니까? (0) | 2020.06.13 |
상수로 채워진 여러 행을 선택하는 방법은 무엇입니까? (0) | 2020.06.13 |
작업 공간에서 몇 가지 특정 객체 만 지우려면 어떻게해야합니까? (0) | 2020.06.13 |