基于索引和数据列查询 pandas 数据框。

5

我有一个数据集,看起来像这样:

data="""cruiseid  year  station  month  day  date        lat        lon         depth_w  taxon                        count  
        AA8704    1987  1        04     13   13-APR-87   35.85      -75.48      18       Centropages_typicus          75343  
        AA8704    1987  1        04     13   13-APR-87   35.85      -75.48      18       Gastropoda                   0  
        AA8704    1987  1        04     13   13-APR-87   35.85      -75.48      18       Calanus_finmarchicus         2340   
        AA8704    1987  1        07     13   13-JUL-87   35.85      -75.48      18       Acartia_spp.                 5616   
        AA8704    1987  1        07     13   13-JUL-87   35.85      -75.48      18       Metridia_lucens              468    
        AA8704    1987  1        08     13   13-AUG-87   35.85      -75.48      18       Evadne_spp.                  0      
        AA8704    1987  1        08     13   13-AUG-87   35.85      -75.48      18       Salpa                        0      
        AA8704    1987  1        08     13   13-AUG-87   35.85      -75.48      18       Oithona_spp.                 468    
"""
datafile = open('data.txt','w')
datafile.write(data)
datafile.close()

我使用以下代码将其读入pandas中:

parse = lambda x: dt.datetime.strptime(x, '%d-%m-%Y')
df = pd.read_csv('data.txt',index_col=0, header=False, parse_dates={"Datetime" : [1,3,4]}, skipinitialspace=True, sep=' ', skiprows=0)

我该如何从这个数据框中生成一个子集,使其包含所有四月份的记录,并且分类(taxon)为'Calanus_finmarchicus'或'Gastropoda'?

我可以使用以下查询语句查询分类(taxon)等于'Calanus_finmarchicus'或'Gastropoda'的数据:

df[(df.taxon == 'Calanus_finmarchicus') | (df.taxon == 'Gastropoda')]

但我在查询时间方面遇到了麻烦,类似于numy的查询方式可能是这样的:
import numpy as np
data = np.genfromtxt('data.txt', dtype=[('cruiseid','S6'), ('year','i4'), ('station','i4'), ('month','i4'), ('day','i4'), ('date','S9'), ('lat','f8'), ('lon','f8'), ('depth_w','i8'), ('taxon','S60'), ('count','i8')], skip_header=1)
selection = [np.where((data['taxon']=='Calanus_finmarchicus') | (data['taxon']=='Gastropoda') & ((data['month']==4) | (data['month']==3)))[0]]
data[selection]

这里有一个笔记本的链接(点击此处),可以重现示例。

4个回答

5
您可以参考 datetimemonth 属性:
>>> df.index.month
array([4, 4, 4, 7, 7, 8, 8, 8], dtype=int32)

>>> df[((df.taxon == 'Calanus_finmarchicus') | (df.taxon == 'Gastropoda'))
...        & (df.index.month == 4)]

           cruiseid  station       date    lat    lon  depth_w  \
Datetime
1987-04-13   AA8704        1  13-APR-87  35.85 -75.48       18
1987-04-13   AA8704        1  13-APR-87  35.85 -75.48       18

                           taxon  count  Unnamed: 11
Datetime
1987-04-13            Gastropoda      0          NaN
1987-04-13  Calanus_finmarchicus   2340          NaN

如果您有一个多列索引,那么在过滤表达式中可以单独引用这些列吗? - Mzzzzzz

2

像其他人说的一样,你可以使用 df.index.month 按月份进行筛选,但我建议还使用 pandas.Series.isin() 来检查你的 taxon 条件:

>>> df[df.taxon.isin(['Calanus_finmarchicus', 'Gastropoda']) & (df.index.month == 4)]
           cruiseid  station       date    lat    lon  depth_w  \
Datetime                                                         
1987-04-13   AA8704        1  13-APR-87  35.85 -75.48       18   
1987-04-13   AA8704        1  13-APR-87  35.85 -75.48       18   

                           taxon  count  Unnamed: 11  
Datetime                                              
1987-04-13            Gastropoda      0          NaN  
1987-04-13  Calanus_finmarchicus   2340          NaN  

1
使用索引的月份属性:
df[(df.index.month == 4) & ((df.taxon == 'Calanus_finmarchicus') | (df.taxon == 'Gastropoda'))]

0

我没有注意语法(括号顺序)和数据框索引属性,这行代码给了我我想要的结果:

results = df[((df.taxon == 'Calanus_finmarchicus') | (df.taxon == 'Gastropoda')) & (df.index.month==4)]  # [df.index.month==4)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接