【发布时间】:2021-05-27 08:20:26
【问题描述】:
我有以下数据集
Date Type Label
2020-03-20 A 1
2020-03-20 A 0
2020-03-19 B 1
2020-03-17 A 1
2020-03-15 C 0
2020-03-19 A 0
2020-03-20 D 1
2020-03-20 A 1
我想在多线图中使用标准化值进行绘制。 下面的代码绘制了不同的时间线
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, figsize=[10,6])
(df.loc[df.Label.eq(1),].groupby(["Date","Type"]).agg({"Type":"count"})
.unstack(1).droplevel(0,axis=1)
.fillna(method="ffill")
.plot(ax=ax, kind="line")
)
但是当我尝试应用规范化时
column_norm=['Type']
df[column_norm] = df[column_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
失败,返回错误:
TypeError: 不支持的操作数类型 -: 'str' 和 'str'
当我计算最小值和最大值时。
你能告诉我如何得到一个 y 轴归一化为 1 的图吗?
【问题讨论】:
-
究竟是什么失败了?
-
当我计算最小值和最大值时出现错误:TypeError: unsupported operand type(s) for -: 'str' and 'str'
-
df['Type']是一个字符串列。从字符串中减去字符串的预期结果是什么? -
@G.Anderson,我相信他上面的
groupby()应该产生整数计数。 -
但无论如何,只要尝试将任何列显式转换为数字,例如
df = df.astype({'column_norm': int}),看看效果如何。
标签: python pandas matplotlib