Please consider these two dataframes that contain demographical info about a single zip code (10001):
df1 = pd.DataFrame([['Enrolled In Public School',2000 ], ['Enrolled In Private School', 100], ['Not Enrolled In School', 1]], columns = ['enrollment type', 'count'], index = ['10001', '10001','10001'])
df2 = pd.DataFrame([12000], columns = ['population'], index = ['10001'])
df1 looks like:
enrollment type count
10001 Enrolled In Public School 2000
10001 Enrolled In Private School 100
10001 Not Enrolled In School 1
df2 looks like:
population
10001 12000
How can I create a multi-index dataframe that looks like below? My goal is then to expand this dataframe for more zipcodes.
You can first reset_index()
on df1
and df2
, merge them together, and then use pandas.pivot_table()
.
df1 = df1.reset_index()
df2 = df2.reset_index()
df = pd.merge(df1, df2, how='left', on='index')
df.columns = ['zipcode', 'enrollment type', 'count', 'population']
df.pivot_table(columns=['enrollment type'], index=['zipcode', 'population'])
Result:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.