簡體   English   中英

在多索引中相互繪制兩個 Pandas 數據框列

[英]Plotting two pandas dataframe columns against each other in multiindex

假設我們有一個 Pandas DataFrame:

df = pd.DataFrame(np.array([[1,2,3,4,5],[3,4,5,6,7]]).T, columns=['a','b'])

print(df)

這給了我:

   a  b
0  1  3
1  2  4
2  3  5
3  4  6
4  5  7

如果我嘗試在“b”列上繪制“a”列,我可以非常簡單地執行以下操作:

df.plot(x='a', y='b')
plt.show()

所以我得到了我的圖表。

但是如果我在列上有一個帶有 MultiIndex 的 DataFrame,那么我有一個問題:

df = pd.DataFrame(np.array([[1,2,3,4,5],[3,4,5,6,7]]).T, columns=[['a','b'],['y','w']])

print(df)

這給了我:

   a  b
   y  w
0  1  3
1  2  4
2  3  5
3  4  6
4  5  7

所以如果我現在這樣做:

df.plot(x=['a','y'], y=['b','w'])
plt.show()

我收到以下錯誤:

File "pandas/_libs/index.pyx", line 117, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 1265, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 1273, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'y'

我做錯了什么嗎?

或者熊貓在使用 MultiIndex 時無法繪圖?

試試這個:

df.set_index(('a','y')).plot()

結果:

在此處輸入圖片說明

我認為這是一種更直接的方法:

df.plot(x=('a','y'), y=('b','w'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM