首页 > 解决方案 > 标准化数据以进行绘图

问题描述

我正在尝试以标准化方式绘制下面显示的数据,以使 y 轴上的最大值等于 1。

数据集:

    %_F     %_M     %_C     %_D    Label
0   0.00    0.00    0.08    0.05    0.0
1   0.00    0.00    0.00    0.14    0.0
2   0.00    0.00    0.10    0.01    1.0
3   0.01    0.01    0.07    0.05    1.0
4   0.00    0.00    0.07    0.14    0.0
6   0.00    0.00    0.07    0.05    0.0
7   0.00    0.00    0.05    0.68    0.0
8   0.00    0.00    0.03    0.09    0.0
9   0.00    0.00    0.04    0.02    0.0
10  0.00    0.00    0.06    0.02    0.0

我尝试如下:

cols_to_norm = ["%_F", "%_M", "%_C", "%_D"]
df[cols_to_norm] = df[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))

但我不完全确定输出。事实上,如果一个情节如下

df.pivot_table(index='Label').plot.bar() 

我得到不同的结果。我认为这是因为我没有在第一个代码中考虑 Label 上的索引。

标签: pythonpandasmatplotlibpivot-table

解决方案


  • 有多种技术规范化
  • 这显示了使用原生熊猫的技术
import io
df = pd.read_csv(io.StringIO("""    %_F     %_M     %_C     %_D    Label
0   0.00    0.00    0.08    0.05    0.0
1   0.00    0.00    0.00    0.14    0.0
2   0.00    0.00    0.10    0.01    1.0
3   0.01    0.01    0.07    0.05    1.0
4   0.00    0.00    0.07    0.14    0.0
6   0.00    0.00    0.07    0.05    0.0
7   0.00    0.00    0.05    0.68    0.0
8   0.00    0.00    0.03    0.09    0.0
9   0.00    0.00    0.04    0.02    0.0
10  0.00    0.00    0.06    0.02    0.0"""), sep="\s+")

fig, ax = plt.subplots(2, figsize=[10,6])
df2 = (df-df.min())/(df.max()-df.min())
df.plot(ax=ax[0], kind="line")
df2.plot(ax=ax[1], kind="line")

在此处输入图像描述


推荐阅读