简体   繁体   中英

Pandas merge pivot_table and a dataframe

how to merge a pandas pivot table and a data frame where the combined column in pivot table is in index and in data frame is in column label

pivot table is

                                 perc                                   
odate                    0001-255-255 2015-09-27 2015-09-28 2015-09-29   
bts_name                                                                 
0001_Durgacomplex_NBSNL           100        100        100        100   
0002_Shivanagar_area_Bdr          100        100        100        100   
0003_Old_city_Bidar               100        100        100        100   
0004_Bidar_Mw_Station             100        100        100        100   
0005_Bidri_colony                 100        100        100        100 

dataframe is

ssaname                bts_name    make tech site_type taluka
0  Bangalore   2882_Brigade_Road_III  HUAWEI   3G     NBSNL   BTS3
1  Bangalore   2883_Infantry_Road_II  HUAWEI   3G        IP   BTS3
2  Bangalore           2884_DVG_Road  HUAWEI   3G     NBSNL   BTS1
3  Bangalore  2886_Kempegowda_Nagara  HUAWEI   3G     NBSNL   BTS1
4  Bangalore     2887_Minerva_Circle  HUAWEI   3G     NBSNL   BTS1

You can try reset index at pivot_table and then you get normal df. After that you can merge dfs Simple example:

df1 = pd.DataFrame({
              'cat':[1,1,1,2,2,2,3,3, 3],
              'val':[1,1,1,1,1,1,1,1, 1]
})
df2 = df1.copy()
pt = pd.pivot_table(df1, index='cat', aggfunc=len)
pt.reset_index(inplace=True)
pt
pd.merge(df2, pt, how='inner', on='cat' )

If you have MultiIndex columns, you must first droplevel and then reset_index

df1 = pd.DataFrame({
              'cat':[1,1,1,2,2,2,3,3, 3],
              'cat2':[1,1,1,1,1,2,2,2,2], 
              'val':[1,1,1,1,1,1,1,1, 1]
})
df2 = df1.copy()
pt = pd.pivot_table(df1, index=['cat'], columns=['cat2'], aggfunc=len)
pt.columns =pt.columns.droplevel(0)
pt.reset_index(inplace=True)
pd.merge(df2, pt, how='inner', on='cat' )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM