簡體   English   中英

Python:計算曲線下的面積

[英]Python: Calculate area under the curve

我有帶有 2 列“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) 值來實現預期的結果,但我想知道是否存在可以完成類似工作的現有函數。

我希望你所說的面積是指 x 軸和曲線之間的面積,因為不可能有開放曲線的面積,所以基於這個假設,我也假設 x 總是遞增的
如果您檢查 pos 和 neg 數據框,它們會變成與您想要的完全不同的形狀。 要計算面積,您需要分別計算x軸上下所有圖形的面積,即識別所有x交叉點並找到交叉點之間的面積

我已經制作了一個通用代碼,您仍然需要添加邊緣情況,其中信號不會以攔截開始或結束

tmp['change'] = tmp['y']*tmp['y'].shift(1)<0 ## points before which intercept would be found
tmp['slope']=(tmp['y']-tmp['y'].shift(1))/(tmp['x']-tmp['x'].shift(1))  ## identify slope
tmp['intersection']=-tmp['y']/tmp['slope']+tmp['x']  ## identify point of intersection
intersections=tmp[tmp['change']==True]  ## only take intersection from points where sign of 'y has changed

intersections=intersections[['intersection']]
intersections.rename(columns={"intersection":"x"}, inplace=True)
intersections['y']=int(0)

tmp = tmp[['x','y']]
tmp=tmp.append(intersections)
tmp=tmp.sort_values(by='x')
tmp=tmp.reset_index(drop=True)

crossing = tmp[tmp['y']==0].index  ## points between which area is to be identified
area=0
for i in range(len(crossing)-1):
    area_tmp=integrate.trapz(tmp[crossing[i]:crossing[i+1]+1]['y'],tmp[crossing[i]:crossing[i+1]+1]['x'])
    area+=abs(area_tmp)
    # print(area_tmp)
print(area)

這給出了 10 的答案,您仍然需要為最后一個三角形添加邊緣情況

PS:無法評論問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM