IT

Pandas DataFrame 색인 이름

lottoking 2020. 7. 25. 10:23
반응형

Pandas DataFrame 색인 이름


DateTime 색인이있는 헤더가없는 CSV 파일이 있습니다. 색인과 열 이름을 바꾸고 싶지만 df.rename ()을 사용하면 열 이름 만 바니다. 곤충? 0.12.0 버전입니다

In [2]: df = pd.read_csv(r'D:\Data\DataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] )

In [3]: df.head()
Out[3]: 
                   1
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

In [4]: df.rename(index={0:'Date'}, columns={1:'SM'}, inplace=True)

In [5]: df.head()
Out[5]: 
                  SM
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

rename법은 등급 값에 적용되는 등급 을 사용 합니다 .
색인 레벨의 이름으로 바꾸려고합니다.

df.index.names = ['Date']

건축가 생각하는 좋은 방법은 열과 색인이 동일한 유형의 객체입니다 ( Index또는 MultiIndex)이며, 전치를 통해 둘을 교환 할 수있는 것입니다.

어떤 이름이 열과 의미를 갖기 때문에 약간 스러우 거기에 몇 가지 예가 더 있습니다.

In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))

In [2]: df
Out[2]: 
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df1 = df.set_index('A')

In [4]: df1
Out[4]: 
   B  C
A      
1  2  3
4  5  6

색인에서 이름을 볼 수있는 용어 1을 사용 합니다.

In [5]: df1.rename(index={1: 'a'})
Out[5]: 
   B  C
A      
a  2  3
4  5  6

In [6]: df1.rename(columns={'B': 'BB'})
Out[6]: 
   BB  C
A       
1   2  3
4   5  6

레벨 이름을 바꾸는 동안 :

In [7]: df1.index.names = ['index']
        df1.columns.names = ['column']

참고 :이 속성은 목록 일뿐 목록 이해 /지도로 이름을 바꿀 수 있습니다.

In [8]: df1
Out[8]: 
column  B  C
index       
1       2  3
4       5  6

선택된 답변에는 현재 rename_axis색인 및 열 수준의 이름을 바꾸는 데 사용할 수있는 방법이 언급되어 있지 않습니다 .


팬더는 지수의 이름을 바꾸는 데 약간 불안합니다. 색인 레벨 이름을 변경하는 데 사용할 수 있는 새로운 DataFrame 메소드가 있습니다.rename_axis

DataFrame을 살펴 보겠습니다

df = pd.DataFrame({'age':[30, 2, 12],
                       'color':['blue', 'green', 'red'],
                       'food':['Steak', 'Lamb', 'Mango'],
                       'height':[165, 70, 120],
                       'score':[4.6, 8.3, 9.0],
                       'state':['NY', 'TX', 'FL']},
                       index = ['Jane', 'Nick', 'Aaron'])

여기에 이미지 설명 입력

이 DataFrame은 각 행 및 열마다 하나의 수준이 있습니다. 행 및 열 색인 모두 이름이 없습니다. 행 색인 레벨 이름을 '이름'으로 변경하십시오.

df.rename_axis('names')

여기에 이미지 설명 입력

rename_axis메소드는 axis다음 변수 를 변경하여 열 레벨 이름을 변경하는 기능도 있습니다.

df.rename_axis('names').rename_axis('attributes', axis='columns')

여기에 이미지 설명 입력

일부 열로 인덱스를 설정하면 열 이름이 새 인덱스 수준 이름이됩니다. 원래 DataFrame에 인덱스 수준을 추가해 보겠습니다.

df1 = df.set_index(['state', 'color'], append=True)
df1

여기에 이미지 설명 입력

원래 색인에 이름이 없는지 확인하십시오. 우리는 여전히 사용할 수 rename_axis있지만 인덱스 레벨의 수와 같은 길이의 목록을 전달해야합니다.

df1.rename_axis(['names', None, 'Colors'])

여기에 이미지 설명 입력

None인덱스 수준 이름을 효과적으로 삭제하는 데 사용할 수 있습니다 .


시리즈는 비슷하게 작동하지만 약간의 차이가 있습니다.

세 가지 인덱스 수준으로 시리즈를 만들어 보겠습니다.

s = df.set_index(['state', 'color'], append=True)['food']
s

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: food, dtype: object

rename_axisDataFrames로했던 것과 비슷하게 사용할 수 있습니다.

s.rename_axis(['Names','States','Colors'])

Names  States  Colors
Jane   NY      blue      Steak
Nick   TX      green      Lamb
Aaron  FL      red       Mango
Name: food, dtype: object

Series 아래에라는 추가 메타 데이터가 있습니다 Name. DataFrame에서 Series를 만들 때이 속성은 열 이름으로 설정됩니다.

문자열 이름을 rename메서드에 전달하여 변경할 수 있습니다.

s.rename('FOOOOOD')

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: FOOOOOD, dtype: object

DataFrames에는이 속성이 없으며 이와 같이 사용하면 실제로 예외가 발생합니다.

df.rename('my dataframe')
TypeError: 'str' object is not callable

Pandas 0.21 이전 rename_axis에는 인덱스 및 열의 값 이름을 바꾸는 데 사용할 수있었습니다 . 더 이상 사용되지 않으므로이 작업을 수행하지 마십시오.


Pandas 버전 0.13 이상에서는 인덱스 수준 이름이 변경 FrozenList되지 않으며 (type ) 더 이상 직접 설정할 수 없습니다. 먼저를 사용 Index.rename()하여 새 인덱스 수준 이름을 인덱스 DataFrame.reindex()에 적용한 다음을 사용 하여 새 인덱스를 DataFrame에 적용해야합니다. 예 :

Pandas 버전 0.13 미만

df.index.names = ['Date']

Pandas 버전> = 0.13의 경우

df = df.reindex(df.index.rename(['Date']))

최신 pandas버전의 경우

df.index = df.index.rename('new name')

또는

df.index.rename('new name', inplace=True)

후자는 데이터 프레임이 모든 속성을 유지해야하는 경우에 필요 합니다.


Index.set_names다음과 같이 사용할 수도 있습니다 .

In [25]: x = pd.DataFrame({'year':[1,1,1,1,2,2,2,2],
   ....:                   'country':['A','A','B','B','A','A','B','B'],
   ....:                   'prod':[1,2,1,2,1,2,1,2],
   ....:                   'val':[10,20,15,25,20,30,25,35]})

In [26]: x = x.set_index(['year','country','prod']).squeeze()

In [27]: x
Out[27]: 
year  country  prod
1     A        1       10
               2       20
      B        1       15
               2       25
2     A        1       20
               2       30
      B        1       25
               2       35
Name: val, dtype: int64
In [28]: x.index = x.index.set_names('foo', level=1)

In [29]: x
Out[29]: 
year  foo  prod
1     A    1       10
           2       20
      B    1       15
           2       25
2     A    1       20
           2       30
      B    1       25
           2       35
Name: val, dtype: int64

열과 인덱스의 이름을 바꾸는 데 동일한 매핑을 사용하려면 다음을 수행 할 수 있습니다.

mapping = {0:'Date', 1:'SM'}
df.index.names = list(map(lambda name: mapping.get(name, name), df.index.names))
df.rename(columns=mapping, inplace=True)

df.index.rename('new name', inplace=True)

나를 위해 일하는 유일한 사람입니다 (pandas 0.22.0).
inplace = True가 없으면 색인 이름이 제 경우에 설정되지 않습니다.

참고 URL : https://stackoverflow.com/questions/19851005/rename-pandas-dataframe-index

반응형