【发布时间】:2021-06-26 11:33:26
【问题描述】:
我有两列“x”、“y”的 Pandas DataFrame:
tmp = pd.DataFrame()
tmp['x'] = [1, 2, 5, 9, 12, 14]
tmp['y'] = [0, 1, -2, 2, -1, 1]
tmp.plot(x = 'x', y = 'y')
ax = plt.gca()
ax.set_aspect('equal')
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
plt.show()
剧情如下:
我想分别得到 y=0 以上和 y=0 以下的三角形区域。
有没有简单的方法可以做到这一点?
我尝试使用集成,但似乎我做错了什么:
pos = tmp[tmp['y']>=0]
neg = tmp[tmp['y']<=0]
print(integrate.trapezoid(pos['y'], pos['x'])) # this gives 18.5 instead of desired 5.5
print(integrate.trapezoid(neg['y'], neg['x'])) # this gives -14.5 instead of desired 5
# seems this does correct calculation, but calculates areas as negative and positive and in total it gives small area
print(integrate.trapezoid(tmp['y'], tmp['x'])) # this gives 0.5 instead of desired 10.5
这是一个更小/更简单的代码来显示我想要做什么。其实我的数据很大。 我想我可以通过在 y = 0 的地方添加相应的 (x, y) 值来达到预期的效果,但我想知道是否有现有的函数可以完成类似的工作。
【问题讨论】:
-
你的意思是高于 y=0 低于 y=0,对吧?
-
@lifezbeautiful 是的,感谢您指出这一点!
-
@Heghine,您的问题似乎与 this question 重复。
标签: python pandas scipy integral