使两个数据帧按照 Python / Pandas 中的某些标准进行交互

Making two dataframes interact following certain criterias in Python / Pandas

我有这个数据框,我称之为 group。它包括很多公司注册处:

group:

                 Ratio                       a
companyid                                       
25             5.13271             1.18846e+06
86             1.19454             2.29432e+09
312            165.962                  547000
...
316            6.77336              3.9294e+07
330            3.56741              4.8953e+07
405        0.000429348             2.32911e+06

我想用 groupa 最大的 10 家公司创建一个新数据框。为此,我使用以下内容:

pdf=group.sort('a',ascending=False)[:10].astype(object)

它为我提供了以下数据框:

pdf:

                 Ratio                       a
companyid                                      
2844          0.782216             4.34118e+09
86             1.19454             2.29432e+09
2177         0.0386724              8.6625e+08
1407           2.08113             3.84293e+08
3094           1.25491              3.3353e+08
1099          0.671924              2.6757e+08
877           0.443107             6.20865e+07
330            3.56741              4.8953e+07
1147           16.9933              3.9313e+07
316            6.77336              3.9294e+07

请注意,此数据框内有 10 家公司,它应该保留 10 家。但是,我只想计算 Ratio 在 -3.95 和 6.40 之间的公司。我需要动态地做到这一点。那么,我需要做的是:

a) 创建一种方法来检查是否有 Ratio 超出范围的公司(在本例中,1147 和 316 超出范围)并将这些公司排除在 pdf:

为此,我使用了以下内容并且工作正常:

for i in pdf['Ratio']:
    if i>6.40:
        b=i
        position=(pdf['Ratio'][pdf['Ratio'] == b]).index
        print(position[0])
        pdf=pd.DataFrame.drop(pdf, position[0])

    if i<-3.95: #check the ones over max and exclude them
        position=(pdf['Ratio'][pdf['Ratio'] == i]).index
        print(position[0])
        pdf=pd.DataFrame.drop(pdf, position[0])

b) 按照a的顺序(从大到小)插入"Group"后面的公司,使pdf再次包含10家公司。好的,我可以这样做:

if 10-(len(pdf.index))>0:
    select=(group).sort('a',ascending=False)[10:10+10-(len(pdf.index))].astype(object)
    pdf=pd.concat((pdf,select))

问题是,在这次互动之后,我需要再次检查新公司 Ratio 是否在 6.40 和 -3.95 之间的范围内。如果有任何公司超出范围,我将不得不将其删除并排入下一个。

如果接下来的任何一个超出范围,我将不得不一次又一次地这样做。我认为它可能与 while 循环有关,但是我是一个初学者并且我不太熟悉使用 while.

也许我误会了你,但在获取 10 个最大的 a 值之前排除所有无效比率行不是很好吗?

例如做:

valid_ratios = group.query('Ratio > -3.95 & Ratio < 6.40')

使用前:

pdf=valid_ratios.sort('a',ascending=False)[:10].astype(object)