sourcetip

Pandas: Excel에서 병합된 헤더 열 구문 분석

fileupload 2023. 8. 21. 21:33
반응형

Pandas: Excel에서 병합된 헤더 열 구문 분석

Excel 시트의 데이터는 다음과 같이 저장됩니다.

   Area     |          Product1     |      Product2        |      Product3
            |      sales|sales.Value|   sales |sales.Value |  sales |sales.Value
  Location1 |    20     | 20000     |      25 |  10000     |   200  | 100
  Location2 |    30     | 30000     |      3  | 12300      |   213  | 10

제품명은 한 달 동안 1000여 개 영역에 대해 "매출 없음"과 "매출 가치" 두 줄의 두 셀이 합쳐진 것입니다.마찬가지로 지난 5년 동안 매월 별도의 파일이 있습니다.또한, 여러 달 동안 새로운 제품이 추가되고 제거되었습니다.따라서 다른 월 파일은 다음과 같습니다.

   Area     |          Product1     |      Product4        |      Product3

포럼은 판다를 이용하여 이 자료를 읽는 가장 좋은 방법을 제안할 수 있습니까?매달 제품 열이 다르기 때문에 인덱스를 사용할 수 없습니다.

위의 초기 형식을 다음으로 변환하는 것이 이상적입니다.

 Area      | Product1.sales|Product1.sales.Value| Product2.sales |Product2.sales.Value | 
 Location1 | 20            | 20000              | 25             | 10000               |  
 Location2 | 30            | 30000              | 3              | 12300               | 

import pandas as pd
xl_file = read_excel("file path", skiprow=2, sheetname=0)
/* since the first two rows are always blank */


                  0            1        2               3                      4
      0          NaN          NaN      NaN       Auto loan                    NaN
      1  Branch Code  Branch Name   Region  No of accounts  Portfolio Outstanding
      2         3000       Name1  Central               0                      0
      3         3001       Name2  Central               0                      0

로 변환하고 싶습니다.Auto loan.No of account,Auto loan.Portfolio Outstanding머리글로.

데이터 프레임이 다음과 같다고 가정합니다.df:

import numpy as np
import pandas as pd

nan = np.nan
df = pd.DataFrame([
    (nan, nan, nan, 'Auto loan', nan)
    , ('Branch Code', 'Branch Name', 'Region', 'No of accounts'
       , 'Portfolio Outstanding')
    , (3000, 'Name1', 'Central', 0, 0)
    , (3001, 'Name2', 'Central', 0, 0)
])

다음과 같이 보이도록 합니다.

             0            1        2               3                      4
0          NaN          NaN      NaN       Auto loan                    NaN
1  Branch Code  Branch Name   Region  No of accounts  Portfolio Outstanding
2         3000       Name1  Central               0                      0
3         3001       Name2  Central               0                      0

그런 다음 먼저 처음 두 행에 NaN을 앞으로 채웁니다(예: '자동 대출' 전파).

df.iloc[0:2] = df.iloc[0:2].fillna(method='ffill', axis=1)

다음으로 빈 문자열로 나머지 NaN을 채웁니다.

df.iloc[0:2] = df.iloc[0:2].fillna('')

이제 두 행을 함께 결합합니다..열 수준 값으로 지정합니다.

df.columns = df.iloc[0:2].apply(lambda x: '.'.join([y for y in x if y]), axis=0)

마지막으로 처음 두 행을 제거합니다.

df = df.iloc[2:]

이것은 수확량

  Branch Code Branch Name   Region Auto loan.No of accounts  \
2        3000      Name1  Central                        0   
3        3001      Name2  Central                        0   

  Auto loan.Portfolio Outstanding  
2                               0  
3                               0  

또는 플랫 열 인덱스를 만드는 대신 다중 인덱스 열을 만들 수 있습니다.

import numpy as np
import pandas as pd

nan = np.nan
df = pd.DataFrame([
    (nan, nan, nan, 'Auto loan', nan)
    , ('Branch Code', 'Branch Name', 'Region', 'No of accounts'
       , 'Portfolio Outstanding')
    , (3000, 'Name1', 'Central', 0, 0)
    , (3001, 'Name2', 'Central', 0, 0)
])
df.iloc[0:2] = df.iloc[0:2].fillna(method='ffill', axis=1)
df.iloc[0:2] = df.iloc[0:2].fillna('Area')

df.columns = pd.MultiIndex.from_tuples(
    zip(*df.iloc[0:2].to_records(index=False).tolist()))
df = df.iloc[2:]

지금이다df다음과 같이 표시됩니다.

         Area                           Auto loan                      
  Branch Code Branch Name   Region No of accounts Portfolio Outstanding
2        3000      Name1  Central              0                     0
3        3001      Name2  Central              0                     0

열이 MultiIndex:

In [275]: df.columns
Out[275]: 
MultiIndex(levels=[[u'Area', u'Auto loan'], [u'Branch Code', u'Branch Name', u'No of accounts', u'Portfolio Outstanding', u'Region']],
           labels=[[0, 0, 0, 1, 1], [0, 1, 4, 2, 3]])

열에는 두 개의 수준이 있습니다.첫 번째 레벨에는 값이 있습니다.[u'Area', u'Auto loan']두 번째는 가치가 있습니다.[u'Branch Code', u'Branch Name', u'No of accounts', u'Portfolio Outstanding', u'Region'].

그런 다음 두 수준의 값을 지정하여 열에 액세스할 수 있습니다.

print(df.loc[:, ('Area', 'Branch Name')])
# 2    Name1
# 3    Name2
# Name: (Area, Branch Name), dtype: object

print(df.loc[:, ('Auto loan', 'No of accounts')])
# 2    0
# 3    0
# Name: (Auto loan, No of accounts), dtype: object

다중 인덱스를 사용하면 특정 수준 값을 가진 모든 열을 쉽게 선택할 수 있습니다.예를 들어 다음과 관련된 하위 데이터 프레임을 선택합니다.Auto loans다음을 사용할 수 있습니다.

In [279]: df.loc[:, 'Auto loan']
Out[279]: 
  No of accounts Portfolio Outstanding
2              0                     0
3              0                     0

다중 색인에서 행 및 열 선택에 대한 자세한 내용은 슬라이서를 사용한 다중 색인화를 참조하십시오.

언급URL : https://stackoverflow.com/questions/27420263/pandas-parse-merged-header-columns-from-excel

반응형