Python Pandas-재 인덱싱
ReindexingDataFrame의 행 레이블 및 열 레이블을 변경합니다. 재 색인 이란 특정 축을 따라 주어진 레이블 세트와 일치하도록 데이터를 일치시키는 것을 의미합니다.
다음과 같은 인덱싱을 통해 여러 작업을 수행 할 수 있습니다.
- 새 레이블 세트와 일치하도록 기존 데이터의 순서를 변경하십시오. 
- 레이블에 대한 데이터가없는 레이블 위치에 결 측값 (NA) 마커를 삽입합니다. 
예
import pandas as pd
import numpy as np
N=20
df = pd.DataFrame({
   'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
   'x': np.linspace(0,stop=N-1,num=N),
   'y': np.random.rand(N),
   'C': np.random.choice(['Low','Medium','High'],N).tolist(),
   'D': np.random.normal(100, 10, size=(N)).tolist()
})
#reindex the DataFrame
df_reindexed = df.reindex(index=[0,2,5], columns=['A', 'C', 'B'])
print df_reindexed이것의 output 다음과 같습니다-
A    C     B
0  2016-01-01  Low   NaN
2  2016-01-03  High  NaN
5  2016-01-06  Low   NaN다른 개체와 정렬하기 위해 다시 색인화
객체를 가져 와서 다른 객체와 동일하게 레이블이 지정되도록 해당 축을 다시 인덱싱 할 수 있습니다. 동일한 내용을 이해하려면 다음 예제를 고려하십시오.
예
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(10,3),columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randn(7,3),columns=['col1','col2','col3'])
df1 = df1.reindex_like(df2)
print df1이것의 output 다음과 같습니다-
col1         col2         col3
0    -2.467652    -1.211687    -0.391761
1    -0.287396     0.522350     0.562512
2    -0.255409    -0.483250     1.866258
3    -1.150467    -0.646493    -0.222462
4     0.152768    -2.056643     1.877233
5    -1.155997     1.528719    -1.343719
6    -1.015606    -1.245936    -0.295275Note − 여기서 df1 DataFrame은 다음과 같이 변경되고 다시 색인화됩니다. df2. 열 이름이 일치해야합니다. 그렇지 않으면 전체 열 레이블에 NAN이 추가됩니다.
재 인덱싱 중 채우기
reindex() 다음과 같이 값을 채우는 방법 인 선택적 매개 변수 방법을 취합니다.
- pad/ffill − 앞으로 값 채우기 
- bfill/backfill − 값을 뒤로 채우기 
- nearest − 가장 가까운 인덱스 값에서 채우기 
예
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])
# Padding NAN's
print df2.reindex_like(df1)
# Now Fill the NAN's with preceding Values
print ("Data Frame with Forward Fill:")
print df2.reindex_like(df1,method='ffill')이것의 output 다음과 같습니다-
col1        col2       col3
0    1.311620   -0.707176   0.599863
1   -0.423455   -0.700265   1.133371
2         NaN         NaN        NaN
3         NaN         NaN        NaN
4         NaN         NaN        NaN
5         NaN         NaN        NaN
Data Frame with Forward Fill:
         col1        col2        col3
0    1.311620   -0.707176    0.599863
1   -0.423455   -0.700265    1.133371
2   -0.423455   -0.700265    1.133371
3   -0.423455   -0.700265    1.133371
4   -0.423455   -0.700265    1.133371
5   -0.423455   -0.700265    1.133371Note − 마지막 4 개 행이 채워집니다.
재색 인화 중 채우기 제한
limit 인수는 재색 인화하는 동안 채우기에 대한 추가 제어를 제공합니다. 제한은 연속 일치의 최대 개수를 지정합니다. 같은 것을 이해하기 위해 다음 예제를 고려해 보겠습니다.
예
import pandas as pd
import numpy as np
 
df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randn(2,3),columns=['col1','col2','col3'])
# Padding NAN's
print df2.reindex_like(df1)
# Now Fill the NAN's with preceding Values
print ("Data Frame with Forward Fill limiting to 1:")
print df2.reindex_like(df1,method='ffill',limit=1)이것의 output 다음과 같습니다-
col1        col2        col3
0    0.247784    2.128727    0.702576
1   -0.055713   -0.021732   -0.174577
2         NaN         NaN         NaN
3         NaN         NaN         NaN
4         NaN         NaN         NaN
5         NaN         NaN         NaN
Data Frame with Forward Fill limiting to 1:
         col1        col2        col3
0    0.247784    2.128727    0.702576
1   -0.055713   -0.021732   -0.174577
2   -0.055713   -0.021732   -0.174577
3         NaN         NaN         NaN
4         NaN         NaN         NaN
5         NaN         NaN         NaNNote− 관찰하십시오. 7 번째 행만 이전 6 번째 행으로 채워집니다. 그런 다음 행은 그대로 유지됩니다.
이름 바꾸기
rename () 메서드를 사용하면 일부 매핑 (dict 또는 Series) 또는 임의의 함수를 기반으로 축의 레이블을 다시 지정할 수 있습니다.
이것을 이해하기 위해 다음 예를 고려해 보겠습니다.
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.randn(6,3),columns=['col1','col2','col3'])
print df1
print ("After renaming the rows and columns:")
print df1.rename(columns={'col1' : 'c1', 'col2' : 'c2'},
index = {0 : 'apple', 1 : 'banana', 2 : 'durian'})이것의 output 다음과 같습니다-
col1        col2        col3
0    0.486791    0.105759    1.540122
1   -0.990237    1.007885   -0.217896
2   -0.483855   -1.645027   -1.194113
3   -0.122316    0.566277   -0.366028
4   -0.231524   -0.721172   -0.112007
5    0.438810    0.000225    0.435479
After renaming the rows and columns:
                c1          c2        col3
apple     0.486791    0.105759    1.540122
banana   -0.990237    1.007885   -0.217896
durian   -0.483855   -1.645027   -1.194113
3        -0.122316    0.566277   -0.366028
4        -0.231524   -0.721172   -0.112007
5         0.438810    0.000225    0.435479rename () 메서드는 inplace기본적으로 False이며 기본 데이터를 복사합니다. 통과하다inplace=True 데이터의 이름을 바꿉니다.