【发布时间】:2018-11-01 19:04:54
【问题描述】:
在玩具示例 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')
它成功了。
问题是,当采用真正的dataFrame时,这种确切的方法不起作用并返回以下错误:
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
有人知道我做错了什么吗?这让我很困惑,因为这种方法确实适用于玩具示例。
提前非常感谢,我希望问题已经足够清楚地说明(这里是新手)。
【问题讨论】:
-
如果你在你的真实数据帧(或至少前几行)中
print(x),你会得到什么? -
这个错误可能是因为你的dataFrame的索引不是你所期望的,即不是从0开始
-
索引/值对列表,dtype:float64。
-
riiiiight,它没有
-
我做了 reset_index 现在就像一个魅力。非常感谢!
标签: python pandas matplotlib