[英]Pandas merge pivot_table and a dataframe
如何合並熊貓數據透視表和數據框,其中數據透視表中的合並列在索引中,而數據框在列標簽中
樞紐分析表現為
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
數據框是
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
您可以嘗試在pivot_table重置索引,然后獲得正常的df。 之后,您可以合並dfs簡單示例:
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' )
如果您有MultiIndex列,則必須先進行droplevel然后再進行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' )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.