报告与另一列的第一个非零值和最后一个零值相对应的列值

2024-06-24 12:23:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧。我想扫描“Krg”列,找到与此列中最后一个零值相对应的行,并从此行报告“Sg”(0.03)。此外,我想报告与第一个非零值“Krg”(0.04)相对应的“Sg”。你知道吗

我可以使用query()实现这一点-请参阅下面的代码。你知道吗

import pandas as pd

col_labels = ['Sg', 'Krg', 'Krw', 'Pc']

df = pd.DataFrame(columns=col_labels)

f = open('EPS.INC', 'r')
for line in f:
    if 'SGWFN' in line:
        print('Reading relative permeability table')
        for line in f:
            line = line.strip()
            if (line.split() and not line.startswith('/') and not line.startswith('--')):
                cols = line.split()
                df=df.append(pd.Series(([float(i) for i in cols]), index=col_labels), ignore_index=True)



print(df.loc[df.query('Krg != 0')['Krg'].idxmin(), 'Sg'])
print(df.loc[(df.query('Krg != 0')['Krg'].idxmin())-1, 'Sg'])
      Sg       Krg       Krw         Pc
0   0.00  0.000000  1.000000   0.000000
1   0.03  0.000000  0.500000   0.091233
2   0.04  0.000518  0.484212   0.093203
3   0.05  0.001624  0.468759   0.095237
4   0.06  0.003171  0.453639   0.097338
5   0.07  0.005098  0.438848   0.099508
6   0.08  0.007367  0.424382   0.101751
7   0.09  0.009953  0.410237   0.104070
8   0.10  0.012835  0.396410   0.106469
9   0.11  0.015999  0.382897   0.108950
10  0.12  0.019431  0.369695   0.111518

代码似乎不太“潘多拉”,似乎很慢。有没有更聪明的方法来获得这些“Sg”值?你知道吗

干杯, D级


Tags: 代码indfforlabels报告linecol
3条回答

对于第一种情况,我们确保'Krg'是0,并且'Krg'列中0之后的值不是0。你知道吗

df.loc[(df['Krg'] == 0.00000)&(df['Krg'] != df['Krg'].shift(-1)), 'Sg']

对于第二种情况,我们使用与上面一种类似的思维过程,但是要确保上面的行是0,并且它们都不是0。你知道吗

df.loc[(df['Krg'].shift(1) == 0.00000)&(df['Krg'] != df['Krg'].shift(1)), 'Sg']

使用%%timeit,我的版本大约快了35%。你知道吗

我们可以通过使用^{}^{}来简化这个过程,它们代表equalnot equal。我们结合^{}^{}得到第一行和最后一行。你知道吗


m = df['Krg'].ne(0)
n = df['Krg'].eq(0)

df.loc[m, 'Sg'].head(1).iloc[0]
df.loc[n, 'Sg'].tail(1).iloc[0]

输出

0.04
0.03

我只是在使用idxmax,并试图加快您原来的职位

s=df.query('Krg != 0')['Krg'].idxmin()# here you only need run idxmax once not twice 
print(df.loc[s, 'Sg'])
print(df.loc[s-1, 'Sg'])

相关问题 更多 >