我有一个数据框,如下所示。我想浏览“ 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
答案 0 :(得分:0)
对于您的第一种情况,我们确保“ Krg”为0,并且“ Krg”列中0以后的值不为0。
particles[i].x
对于第二种情况,我们使用与上述类似的思维过程,但请确保上面的行改为0,并且两者都为0。
df.loc[(df['Krg'] == 0.00000)&(df['Krg'] != df['Krg'].shift(-1)), 'Sg']
使用%% timeit,我的版本快了35%。
答案 1 :(得分:0)
我们可以使用Series.eq
和Series.ne
(它们分别代表equal
和not equal
来简化此过程。我们将DataFrame.head
和DataFrame.tail
结合起来,得到他的第一行和最后一行。
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
答案 2 :(得分:0)
我只是使用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'])