我有一个如下所示的数据帧。我想扫描“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级
对于第一种情况,我们确保'Krg'是0,并且'Krg'列中0之后的值不是0。你知道吗
对于第二种情况,我们使用与上面一种类似的思维过程,但是要确保上面的行是0,并且它们都不是0。你知道吗
使用%%timeit,我的版本大约快了35%。你知道吗
我们可以通过使用^{} 和^{} 来简化这个过程,它们代表} 和^{} 得到第一行和最后一行。你知道吗
equal
和not equal
。我们结合^{输出
我只是在使用idxmax,并试图加快您原来的职位
相关问题 更多 >
编程相关推荐