嗨,我使用此代碼隨機用 NaN 值填充我的資料集:
total_cells = df.shape[0] * df.shape[1]
df = df.reset_index().melt(id_vars = "index")
df.loc[np.random.randint(0, total_cells, int(total_cells * .25)), "value"] = np.NaN
df.pivot(index = "index", columns = "variable")
透視后,我檢查的列看起來像
df.columns.to_list()
[('value', 'AGE'), ('value','DATE'),.........,('value','TIME')]
但我希望它們只是 ['AGE', 'DATE',...,'TIME']。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
將引數添加values到pivot更簡單的方法:
df.pivot(index = "index", columns = "variable", value='value')
或者:
df.pivot(index = "index", columns = "variable").droplevel(axis=1, level=0)
uj5u.com熱心網友回復:
lz,試試這個。
df.pivot(index = "index", columns = "variable", columns='value')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331596.html
下一篇:用字串模式映射熊貓系列
