首页 > 解决方案 > matplotlib:绘制一条迭代数据框行的线

问题描述

在玩具示例 dataFrame 中有 2 组坐标:x, y 和 ex, ey。

d = {'x': [1, 2, 3, 4], 'y': [3, 3, 3, 3], 'ex': [1, 2, 3, 4], 'ey': [6, 6, 6, 6]}
toy = pd.DataFrame(data=d)

每组需要先散点图,然后用一条线连接。

plt.scatter(toy['x'],toy['y'], color='b')
plt.scatter(toy['ex'],toy['ey'], color='g')
plt.plot(toy['x'],toy['y'], color='b')
plt.plot(toy['ex'],toy['ey'], color='g')

最后,同一行中出现的集合之间的样本必须连接,也可以通过线连接。这是通过将每一列作为 pandas.Series 类型来实现的

x = toy['x']
ex = toy['ex']
y = toy['y']
ey = toy['ey']

并在绘图函数中迭代它们

for i in range(len(x)):
    plt.plot([x[i], ex[i]], [y[i], ey[i]], color='cyan')

它奏效了。

问题是,当采用真正的数据帧时,这种确切的方法不起作用并返回以下错误:


KeyError                                  Traceback (most recent call last)
<ipython-input-174-aa1b4849722f> in <module>()
     21 
     22 for i in range(len(x)):
---> 23     plt.plot([x[i], ex[i]], [y[i], ey[i]], color='cyan')
     24 
     25 plt.show()

/usr/lib/python3/dist-packages/pandas/core/series.py in __getitem__(self, key)
    601         key = com._apply_if_callable(key, self)
    602         try:
--> 603             result = self.index.get_value(self, key)
    604 
    605             if not is_scalar(result):

/usr/lib/python3/dist-packages/pandas/indexes/base.py in get_value(self, series, key)
   2167         try:
   2168             return self._engine.get_value(s, k,
-> 2169                                           tz=getattr(series.dtype, 'tz', None))
   2170         except KeyError as e1:
   2171             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3557)()

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3240)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8564)()

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:8508)()

KeyError: 0

有人知道我做错了什么吗?这让我很困惑,因为这种方法确实适用于玩具示例。

提前非常感谢,我希望问题已经足够清楚(这里是新手)。

标签: pythonpandasmatplotlib

解决方案


好的,所以在真实的数据帧中,只选择了一个数据子集进行绘图。因此,子集的索引不是以 0 开头的,这显然使 Python 感到困惑。解决方案是使用以下方法重置索引:

df = df.reset_index(drop=True)

感谢帮助 :)


推荐阅读