![](/img/trans.png)
[英]Python Pandas: for a multi-indexed dataframe, how to interchange row and one indexed column?
[英]Python Pandas: drop columns from multi-indexed dataframe. Column removed, but column name remains
我正在嘗試創建一個多索引數據框的視圖。 我想知道為什么列名稱在列被刪除后仍保留。
import panda as pd
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6, 7, 8],
'x': [2, 2, 2, 2, 12, 12, 12, 12],
'y': [5.91, 4.43, 5.22, 1.31, 6.32, 6.78, 4.65, 1.98],
'z': [18.61, 17.60, 18.27, 16.18, 16.81, 16.37, 67.07, 46.00]})
pivot_df = df.pivot_table(index=['id'],columns=['x'],values=['y','z'])
[output]
>>> pivot_df
y z
x 2 12 2 12
id
1 5.91 NaN 18.61 NaN
2 4.43 NaN 17.60 NaN
3 5.22 NaN 18.27 NaN
4 1.31 NaN 16.18 NaN
5 NaN 6.32 NaN 16.81
6 NaN 6.78 NaN 16.37
7 NaN 4.65 NaN 67.07
8 NaN 1.98 NaN 46.00
>>> pivot_df.columns
MultiIndex(levels=[['y', 'z'], [2, 12]],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=[None, 'x'])
在上面的代碼中,我可以在0級看到預期的['y','z']。 現在我試圖擺脫'z'下的列。
new_pivot_df = pivot_df.drop('z',axis=1,level=0)
[output]
>>> new_pivot_df
y
x 2 12
id
1 5.91 NaN
2 4.43 NaN
3 5.22 NaN
4 1.31 NaN
5 NaN 6.32
6 NaN 6.78
7 NaN 4.65
8 NaN 1.98
>>> new_pivot_df.columns
MultiIndex(levels=[['y', 'z'], [2, 12]],
labels=[[0, 0], [0, 1]],
names=[None, 'x'])
在上面的代碼中,new_pivot_df顯示'z'被刪除。 但是,當我檢查new_pivot_df.columns時,我仍然在列名中看到'z'。 我想了解為什么會這樣,我正在尋找一個優雅的建議,從多索引數據框中刪除列(數據和名稱)。
先感謝您。
版本0.20.1中的新功能remove_unused_levels()
:
new_pivot_df.columns = new_pivot_df.columns.remove_unused_levels()
new_pivot_df.columns
輸出:
MultiIndex(levels=[['y'], [2, 12]],
labels=[[0, 0], [0, 1]],
names=[None, 'x'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.