亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將多索引列附加到空數據框中

將多索引列附加到空數據框中

catspeake 2021-07-08 14:53:10
以下問題我得到了一個像這樣的數據幀:df = pd.DataFrame(columns=pd.MultiIndex(levels=[["foo","baa"],["x","y","z"]], labels=[[0,0,0,1,1,1],[0,1,2,0,1,2]]), index=[0,1,2,3], data=np.random.rand(4,6))         foo                           baa                              x         y         z         x         y         z0  0.263780  0.942880  0.176744  0.914854  0.920735  0.5736921  0.601317  0.584691  0.288536  0.832064  0.095142  0.1860452  0.807323  0.075620  0.399703  0.936894  0.168441  0.4689843  0.871293  0.324817  0.395784  0.133541  0.365586  0.615219我想說 foo 到一個新的 DataFrame 完全空構造如下:r_df = pd.DataFrame(index=df.index)Empty DataFrameColumns: []Index: [0, 1, 2, 3]它應該是這樣的:         foo          x         y         z0  0.263780  0.942880  0.1767441  0.601317  0.584691  0.2885362  0.807323  0.075620  0.3997033  0.871293  0.324817  0.395784我是這樣嘗試的:for label in df.columns.levels[0]:    data = df[label]    for row in data.index:        r_df.loc[row,(label,"x")] = data["x"]        r_df.loc[row,(label,"y")] = data["y"]        r_df.loc[row,(label,"z")] = data["z"]我認為這可以工作,因為多索引可以被 tubles 引用,但它沒有。
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

嘗試使用以下方法df.xs從 multiIndex 中進行選擇并保持水平:


r_df = df.xs('foo', axis=1, level=0, drop_level=False)

如果你想在下面追加一個新列,foo你可以這樣做:


df.loc[:,('foo','m')] = 0

如果您想在level=0(與 相同級別foo)追加一個新列


# with no col in level 1

df.loc[:, 'bar'] = 0 


# with col in level 0 and 1

df.loc[:,('bar','m')] = 0


查看完整回答
反對 回復 2021-07-13
  • 1 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號