between()函数
1 between函数返回一个布尔量,即如果在该范围内,返回True,否则返回False.
注意between()中括号内是左闭右闭区间
在dataframe中常可用来通过选择某一列元素的范围来选择另一列或几列.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import pandas as pd import numpy as np df = pd.DataFrame(np.arange(24).reshape(6,4), columns=list('ABCD')) print(df) a = df['A'].between(3,13) # 可直接利用a选中满足范围的所有行 print('df[a] is: \n', df[a]) # 利用a选中某一列 # 注意这里的两种类型不同,第一种是series,第二种是Dataframe,加不加[]的微妙区别 r1 = df[a]['D'] print(r1) print('r1的类型是:', type(r1)) r2 = df[a][['D']] print(r2) print('r2的类型是:', type(r2)) # 选中某两列 print(df[a][['D','C']]) #注意between()中括号内是左闭右闭区间,所以可以用如下方式写,相当与筛选某一元素 print(df[df['A'].between(12,12)][['A','B']]) # A B C D # 0 0 1 2 3 # 1 4 5 6 7 # 2 8 9 10 11 # 3 12 13 14 15 # 4 16 17 18 19 # 5 20 21 22 23 # df[a] is: # A B C D # 1 4 5 6 7 # 2 8 9 10 11 # 3 12 13 14 15 # 1 7 # 2 11 # 3 15 # Name: D, dtype: int64 # r1的类型是: <class 'pandas.core.series.Series'> # D # 1 7 # 2 11 # 3 15 # r2的类型是: <class 'pandas.core.frame.DataFrame'> # D C # 1 7 6 # 2 11 10 # 3 15 14 # A B # 3 12 13
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(24).reshape(6,4), columns=list('ABCD'))
print(df)
a = df['A'].between(3,13)
# 可直接利用a选中满足范围的所有行
print('df[a] is: \n', df[a])
# 利用a选中某一列
# 注意这里的两种类型不同,第一种是series,第二种是Dataframe,加不加[]的微妙区别
r1 = df[a]['D']
print(r1)
print('r1的类型是:', type(r1))
r2 = df[a][['D']]
print(r2)
print('r2的类型是:', type(r2))
# 选中某两列
print(df[a][['D','C']])
# A B C D
# 0 0 1 2 3
# 1 4 5 6 7
# 2 8 9 10 11
# 3 12 13 14 15
# 4 16 17 18 19
# 5 20 21 22 23
# df[a] is:
# A B C D
# 1 4 5 6 7
# 2 8 9 10 11
# 3 12 13 14 15
# 1 7
# 2 11
# 3 15
# Name: D, dtype: int64
# r1的类型是: <class 'pandas.core.series.Series'>
# D
# 1 7
# 2 11
# 3 15
# r2的类型是: <class 'pandas.core.frame.DataFrame'>
# D C
# 1 7 6
# 2 11 10
# 3 15