为了账号安全,请及时绑定邮箱和手机立即绑定

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条经验 获得超7个赞

另一个选项建立在您拥有的熔化基础上,并稍后导出重要性列:

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


查看完整回答
反对 回复 2023-07-05
  • 2 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信