如何创建指示给定数据帧的行min和max的数据帧?

2024-10-16 22:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要生成一个矩阵作为自动图表创建过程的条件格式的输入。我的接收同事必须显示数字,并给每行的最大值和最小值一个相关的颜色。对于他的过程,第二个矩阵的条目表示行分钟和最大值将是理想的。 那我需要送什么

假设我有以下数据帧:

Cat Product Brand1  Brand2  Brand3
A   a   6   9   5
A   b   11  7   7
A   c   9   5   5
B   d   7   3   10
B   e   5   8   8
B   f   10  6   6
C   g   8   4   4
C   h   6   2   9
C   i   4   7   7

由此,我想生成以下数据帧,其中“1”表示行最大值,“2”表示行最小值:

Cat Product Brand1  Brand2  Brand3
A   a   0   1   2
A   b   1   2   2
A   c   1   2   2
B   d   0   2   1
B   e   2   1   1
B   f   1   2   2
C   g   1   2   2
C   h   0   2   1
C   i   2   1   1

指标“1”和“2”可以是其他的,甚至是字母或别的什么。零也可以是na

如何做到这一点


Tags: 数据颜色过程格式图表条目矩阵数字
1条回答
网友
1楼 · 发布于 2024-10-16 22:25:25

可以使用^{}将值替换为^{}创建的掩码:

df = df.set_index(['Cat','Product'])
m1 = df.eq(df.max(axis=1), axis=0)
m2 = df.eq(df.min(axis=1), axis=0)
df = pd.DataFrame(np.where(m1, 1, np.where(m2, 2, 0)), index=df.index, columns=df.columns)
df = df.reset_index()
print (df)
  Cat Product  Brand1  Brand2  Brand3
0   A       a       0       1       2
1   A       b       1       2       2
2   A       c       1       2       2
3   B       d       0       2       1
4   B       e       2       1       1
5   B       f       1       2       2
6   C       g       1       2       2
7   C       h       0       2       1
8   C       i       2       1       1

另一种解决方案:

df = df.set_index(['Cat','Product'])
m1 = df.values == df.values.max(axis=1)[:, None]
m2 = df.values == df.values.min(axis=1)[:, None]
df = pd.DataFrame(np.where(m1, 1, np.where(m2, 2, 0)), index=df.index, columns=df.columns)
df = df.reset_index()
print (df)
  Cat Product  Brand1  Brand2  Brand3
0   A       a       0       1       2
1   A       b       1       2       2
2   A       c       1       2       2
3   B       d       0       2       1
4   B       e       2       1       1
5   B       f       1       2       2
6   C       g       1       2       2
7   C       h       0       2       1
8   C       i       2       1       1

相关问题 更多 >