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

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

pandas.melt 之后保留列索引嗎?

pandas.melt 之后保留列索引嗎?

長風秋雁 2023-07-05 09:59:56
我有一個數據框,其值隨時間變化。例如,我在街道上觀察到的汽車數量:df = pd.DataFrame(    [{'Orange': 0, 'Green': 2, 'Blue': 1},     {'Orange': 2, 'Green': 4, 'Blue': 4},     {'Orange': 1, 'Green': 3, 'Blue': 10}    ])我想創建圖表來突出顯示價值最高的汽車。所以我按最大值排序。df.loc[:, df.max().sort_values(ascending=False).index]   Blue  Green  Orange0     1      2       01     4      4       22    10      3       1我正在使用seaborn 來創建這些圖表。據我了解,我需要將這種表示形式融合為整潔的格式。tidy = pd.melt(df.reset_index(), id_vars=['index'], var_name='color', value_name='number')   index   color  number0      0    Blue      11      1    Blue      42      2    Blue     103      0   Green      24      1   Green      45      2   Green      36      0  Orange      07      1  Orange      28      2  Orange      1如何在數據框熔化之前添加代表列順序的列?   index   color  number   importance0      0    Blue      1            01      1    Blue      4            02      2    Blue     10            03      0   Green      2            14      1   Green      4            15      2   Green      3            16      0  Orange      0            2 7      1  Orange      2            28      2  Orange      1            2我發現熔化后仍然可以找到最大列,但我不確定如何將其作為新列添加到數據框中:tidy.groupby('color').number.max().sort_values(ascending=False).indexIndex(['Blue', 'Green', 'Orange'], dtype='object', name='color')編輯 為了澄清,我將其繪制在折線圖上。axes = sns.relplot(data=tidy, x='index', y='number', hue='color', kind="line")圖表目前的樣子是這樣的:我想使用重要性數據來:對線條進行顏色/加粗,或者將圖形拆分為多個圖形,所以它看起來像這樣
查看完整描述

2 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

MultiIndex您可以在柱子上制作一個,然后將兩層堆疊起來。


# Map color to importance

d = (df.max().rank(method='dense', ascending=False)-1).astype(int)


df.columns = pd.MultiIndex.from_arrays([df.columns, df.columns.map(d)],

                                       names=['color', 'importance'])

#color      Orange Green Blue

#importance      2     1    0

#0               0     2    1

#1               2     4    4

#2               1     3   10


df = df.rename_axis(index='index').stack([0,1]).to_frame('value').reset_index()

   index   color  importance  value

0      0    Blue           0    1.0

1      0   Green           1    2.0

2      0  Orange           2    0.0

3      1    Blue           0    4.0

4      1   Green           1    4.0

5      1  Orange           2    2.0

6      2    Blue           0   10.0

7      2   Green           1    3.0

8      2  Orange           2    1.0


查看完整回答
反對 回復 2023-07-05
?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

另一個選項建立在您擁有的熔化基礎上,并稍后導出重要性列:

tidy["importance"] = tidy["color"].map(df.columns.to_list().index)


查看完整回答
反對 回復 2023-07-05
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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