给定两个值,我如何获得这两个值之间的所有值。谢谢
例如:
数据帧:
Quarter GDP
0 1947q1 243.1
1 1947q2 246.3
2 1947q3 250.1
3 1947q4 260.3
4 1948q1 266.2
5 1948q2 272.9
6 1948q3 279.5
7 1948q4 280.7
8 1949q1 275.4
9 1949q2 271.7
10 1949q3 273.3
11 1949q4 271.0
12 1950q1 281.2
13 1950q2 290.7
14 1950q3 308.5
15 1950q4 320.3
16 1951q1 336.4
鉴于1947q3和1948q4,我需要获得(包括)这两个值之间的所有数据
2 1947q3 250.1
3 1947q4 260.3
4 1948q1 266.2
5 1948q2 272.9
6 1948q3 279.5
7 1948q4 280.7
答案 0 :(得分:1)
这将为您提供所需的结果
df[(df['Quarter'] >= '1947q3') & (df['Quarter'] <= '1948q4')]
Quarter GDP
2 1947q3 250.1
3 1947q4 260.3
4 1948q1 266.2
5 1948q2 272.9
6 1948q3 279.5
7 1948q4 280.7
你也可以使用.between
df[df['Quarter'].between('1947q3', '1948q4', inclusive=True)]
答案 1 :(得分:0)
将数据放入dataframe.txt
f = open('dataframe.txt', 'r')
f_r = f.readline()
data = []
while f_r:
infos = f_r.split(' ')
infos = [info.strip() for info in infos if info]
if len(infos) == 3:
data.append((infos[1], infos[2]))
f_r = f.readline()
def get_rangedata_by_quarter(quarter_s, quarter_b):
""" quarter_s is the small one
quarter_b is the big one
"""
for info in data:
quarter = info[0]
if quarter >= quarter_s and quarter <= quarter_b:
print quarter, info[1]
get_rangedata_by_quarter('1947q3', '1948q4')