1 回答

TA貢獻1827條經(jīng)驗 獲得超8個贊
首先合并這些列單列:
all_items = pd.concat([df.ITEM_1, df.ITEM_2])
all_items
Out[8]:
ID
279 Delhi
224 Kanpur
221 Delhi
329 Kannauj
333 Delhi
279 Msc
224 Kanpur
221 Kanpur
329 Phd
333 Kanpur
dtype: object
然后,將其合并回 df:
temp_df = pd.concat([df[["GROUP"]].copy(), df[["GROUP"]].copy()])
temp_df["ITEM"] = all_items
temp_df.reset_index(inplace=True)
temp_df["temp_col"] = 1
temp_df
Out[15]:
ID GROUP ITEM temp_col
0 279 BLACK Delhi 1
1 224 BLACK Kanpur 1
2 221 BLUE Delhi 1
3 329 GREEN Kannauj 1
4 333 BLACK Delhi 1
5 279 BLACK Msc 1
6 224 BLACK Kanpur 1
7 221 BLUE Kanpur 1
8 329 GREEN Phd 1
9 333 BLACK Kanpur 1
最后轉(zhuǎn)一下,
my_pivot = temp_df.pivot_table(values="temp_col", index="GROUP", columns="ITEM", aggfunc=np.sum, fill_value=0)
my_pivot = my_pivot / len(df)
# my_pivot / len (df) # <-- changing this to
to_div = my_pivot.aggregate(np.sum, axis=1) # <-- this and
my_pivot = my_pivot.div(to_div, axis=0) # <-- this
Out[31]:
ITEM Delhi Kannauj Kanpur Msc Phd
GROUP
BLACK 0.333333 0.0 0.5 0.166667 0.0
BLUE 0.500000 0.0 0.5 0.000000 0.0
GREEN 0.000000 0.5 0.0 0.000000 0.5
完畢。
添加回答
舉報