2017-03-10 46 views
0

給定兩個值,如何獲取這兩個值之間的所有值。謝謝通過給出兩個值獲取分片數據框

例如:

數據框:

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 

回答

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)] 
+0

不錯。謝謝 – galaxyan

+0

'df.loc []'是推薦的索引語法:[相關熊貓文檔](http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy) – Jakub

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') 
相關問題