Python Pandas – 返回区间的中点
在这篇文章中,我们将讨论如何使用python编程语言中的pandas返回给定区间的中点。
Pandas Interval.mid属性用于查找区间的中点。它返回区间的中点。中点是一个区间的两点的中心。它是一个区间中与上限和下限等距的点。
示例 1:
导入Pandas包并创建一个区间。Interval.left用于检索该区间的左边界。Interval.right 用于检索区间的右边界。Interval.mid 用于查找区间的中点。Interval.length用于查找区间的长度。
# import packages
import pandas as pd
  
# creating 1st interval
interval1 = pd.Interval(0, 10)
  
print('The interval\'s left bound is : ' + str(interval1.left))
print('The interval\'s right bound is : ' + str(interval1.right))
print('The length of the interval is : ' + str(interval1.length))
print('mid point of the interval is : '+str(interval1.mid))
print(interval1.closed)
输出:
The interval's left bound is : 0
The interval's right bound is : 10
The length of the interval is : 10
mid point of the interval is : 5.0
right
Special Case:
我们也可以通过使用公式(Interval.left+Interval.right)/2来检查,而不是使用interval.mid属性。返回的结果是一样的。
# import packages
import pandas as pd
  
# creating 1st interval
interval1 = pd.Interval(0, 10)
  
print('The interval\'s left bound is : ' + str(interval1.left))
print('The interval\'s right bound is :  : ' + str(interval1.right))
print('The length of the interval is : ' + str(interval1.length))
print('mid point of the interval is : ' + str((interval1.left+interval1.right)/2))
print(interval1.closed)
输出:
The interval's left bound is : 0
The interval's right bound is : 10
The length of the interval is : 10
mid point of the interval is : 5.0
right
示例 2:
在这个例子中,我们使用了封闭参数,一种情况是封闭是 “两者”,另一种情况是封闭既不是也不是开放区间。一个封闭区间有它的最左边的边界和最右边的边界。一个开放区间不包括其最左边界和最右边界。但是在最近的pandas版本中,两种情况的结果是一样的。
# import packages
import pandas as pd
  
# creating intervals
# an interval closed on both sides a<=x<=b
interval1 = pd.Interval(0, 10, closed='both')
  
# an open interval a<x<b. the ends aren't included.
interval2 = pd.Interval(15, 25, closed='neither')
print('interval1\'s left bound is : ' + str(interval1.left))
print('interval1\'s right bound is : ' + str(interval1.right))
print('The length of interval1 is : ' + str(interval1.length))
print('mid point of the interval1 is : '+str(interval1.mid))
print(interval1.closed)
  
print('interval2\'s left bound is : ' + str(interval2.left))
print('interval2\'s right bound is :  ' + str(interval2.right))
print('The length of interval2 is : ' + str(interval2.length))
print('mid point of the interval1 is : '+str(interval2.mid))
print(interval2.closed)
输出:
interval1's left bound is : 0
interval1's right bound is : 10
The length of interval1 is : 10
mid point of the interval1 is : 5.0
both
interval2's left bound is : 15
interval2's right bound is :  25
The length of interval2 is : 10
mid point of the interval1 is : 20.0
neither
 极客教程
极客教程