2017-03-22 1 views
1

나는이 프레임이인덱스와 값이 같은 열에있을 때 다중 인덱스 피벗을 수행하는 방법은 무엇입니까?</p> <pre><code>regions = pd.read_html('http://www.mapsofworld.com/usa/usa-maps/united-states-regional-maps.html') messy_regions = regions[8] </code></pre> <p>이 같은 산출 :

|0 |  1 
--- |---| --- 
0| Region 1 (The Northeast)| nan 
1| Division 1 (New England)| Division 2 (Middle Atlantic) 
2| Maine      | New York 
3| New Hampshire    | Pennsylvania 
4| Vermont     | New Jersey 
5| Massachusetts    |nan 
6| Rhode Island    |nan 
7| Connecticut    | nan 
8| Region 2 (The Midwest) | nan 
9| Division 3 (East North Central)| Division 4 (West North Central) 
10| Wisconsin  |    North Dakota 
11| Michigan  |    South Dakota 
12| Illinois |    Nebraska 

목적이 단정 한 dataframe 수 있도록하는 것입니다 그리고 내가이 지역을 얻기 위해 피벗 필요가 있다고 생각하고 분할을 정확한 지역/부서에서 값으로 상태와 함께 표시합니다. 일단 그 모양이되면 원하는 모양으로 녹을 수 있습니다. 비록 내가 열 머리글이 될 것이라고 밖으로 추출하는 방법을 알아낼 수 없습니다. 어떤 도움이라도 올바르게 평가되고 적어도 올바른 방향으로 나아갈 수 있습니다.

답변

1

당신은 사용할 수 있습니다

url = 'http://www.mapsofworld.com/usa/usa-maps/united-states-regional-maps.html' 
#input dataframe with columns a, b 
df = pd.read_html(url)[8] 
df.columns = ['a','b'] 

#extract Region data to new column 
df['Region'] = df['a'].where(df['a'].str.contains('Region', na=False)).ffill() 
#reshaping, remove rows with NaNs, remove column variable 
df = pd.melt(df, id_vars='Region', value_name='Names') 
     .sort_values(['Region', 'variable']) 
     .dropna() 
     .drop('variable', axis=1) 
#extract Division data to new column 
df['Division'] = df['Names'].where(df['Names'].str.contains('Division', na=False)).ffill() 
#remove duplicates from column Names, change order of columns 
df = df[(df.Division != df.Names) & (df.Region != df.Names)] 
     .reset_index(drop=False) 
     .reindex_axis(['Region','Division','Names'], axis=1) 
#temporaly display all columns 
with pd.option_context('display.expand_frame_repr', False): 
    print (df) 

         Region       Division     Names 
0 Region 1 (The Northeast)   Division 1 (New England)     Maine 
1 Region 1 (The Northeast)   Division 1 (New England)   New Hampshire 
2 Region 1 (The Northeast)   Division 1 (New England)    Vermont 
3 Region 1 (The Northeast)   Division 1 (New England)   Massachusetts 
4 Region 1 (The Northeast)   Division 1 (New England)   Rhode Island 
5 Region 1 (The Northeast)   Division 1 (New England)   Connecticut 
6 Region 1 (The Northeast)  Division 2 (Middle Atlantic)    New York 
7 Region 1 (The Northeast)  Division 2 (Middle Atlantic)   Pennsylvania 
8 Region 1 (The Northeast)  Division 2 (Middle Atlantic)   New Jersey 
9  Region 2 (The Midwest) Division 3 (East North Central)    Wisconsin 
10 Region 2 (The Midwest) Division 3 (East North Central)    Michigan 
11 Region 2 (The Midwest) Division 3 (East North Central)    Illinois 
12 Region 2 (The Midwest) Division 3 (East North Central)    Indiana 
13 Region 2 (The Midwest) Division 3 (East North Central)     Ohio 
... 
... 
+0

신난다! 너는이 표정을 아주 쉽게 만들었다. 각 단계를 더 잘 이해하기 위해이 단계를 진행할 것입니다. – Nick

+0

다행이 당신을 도울 수 있습니다. 또한 괄호 안의 값이 도움이된다면 [this answers] (http://stackoverflow.com/q/41386443/2901002). 좋은 날. – jezrael

관련 문제