我想绘制每年使用 {a, b} 对的折线图。
X 轴应为年份,y 轴应为用法。
这是我的数据集。
a b year usage
a2 10104 2011 7.292787
a0 10104 2012 43.545533
b0 12011 2009 96.130359
b1 12011 2009 7.658487
b1 14102 2010 6.975572
使用pivot_table
重新排列数据,使得我有组合a
和b
在列,year
在索引中。
但是,一旦我们进行了旋转,可能会丢失数据。通过interpolate
与index
参数一起使用,我们用插值填充缺失数据,同时保持与索引值的相对变化成比例。当索引值不是均匀分隔时,这很重要,例如[2005, 2006, 2008]
. 如果索引是统一分隔的,那么使用index
不会有什么坏处,因为它和默认的一样。
d1 = df.pivot_table('usage', 'year', ['a', 'b']).interpolate('index')
d1.index = pd.PeriodIndex(d1.index, freq='A')
d1.plot()
对@jezrael 评论的回应
观察数据的样子是有益的 interpolate
d1 = df.pivot_table('usage', 'year', ['a', 'b'])
d1.index = pd.PeriodIndex(d1.index, freq='A')
d1
a a0 a2 b0 b1
b 10104 10104 12011 12011 14102
year
2009 NaN NaN 96.130359 7.658487 NaN
2010 NaN NaN NaN NaN 6.975572
2011 NaN 7.292787 NaN NaN NaN
2012 43.545533 NaN NaN NaN NaN
在这种情况下,我们看不到会发生什么。但我想象有更多的数据,我们会看到NaN
稀疏数据之间的差距。我们可以按比例填充,而不是向前填充。
d1 = df.pivot_table('usage', 'year', ['a', 'b']).interpolate('index')
d1.index = pd.PeriodIndex(d1.index, freq='A')
d1
a a0 a2 b0 b1
b 10104 10104 12011 12011 14102
year
2009 NaN NaN 96.130359 7.658487 NaN
2010 NaN NaN 96.130359 7.658487 6.975572
2011 NaN 7.292787 96.130359 7.658487 6.975572
2012 43.545533 7.292787 96.130359 7.658487 6.975572
再说一次,这将显示出只有更多数据的好处。与这些数据一样,我们只能观察到有限的前向填充。
关于mean
注意,我使用pivot_table
和pivot_table
处理的事情之一是index/column
规范中是否存在重复项。它将使用aggfunc
. 默认情况下,该功能是mean
. 但是,在这种情况下,根据已提供的数据,没有重复的a/b/year
组合。因此,没有发生聚合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句