大Pandas柱内作业效率高

2024-04-26 18:56:50 发布

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

给定一个pandas.DataFrame、一个列表和一个特殊值,我正在寻找一种优雅的方法:

In a particular column of the df, every time the special value is encountered, check whether the preceding value in the series is in the list.

如果返回前面的值。你知道吗

如果返回一个值并检查。你知道吗

一个有效的实现是:

ser = [1, 2, 0, 2, 3, 1, 4, 7, 2]
d = dict()
relevant =  [0,1]
df = pd.DataFrame([list(range(len(ser))), ser]).transpose()

for j in range(df.shape[0]):
    if df.iloc[j,1]==2:
        k=1
        while True:
            if df.iloc[j-k,1] in relevant:
                d[j] = df.iloc[j-k,1]
                break
            else:
                k+=1

这将提供:

d
{1: 1, 3: 0, 8: 1}

我知道我可以使用shift函数,但是当我使用这个函数时,我有一个循环。我想知道什么是最好的方式做到这一点与优雅,如果可能的速度没有循环。你知道吗


Tags: the函数indataframepandasdf列表if
1条回答
网友
1楼 · 发布于 2024-04-26 18:56:50

我相信你至少需要一个循环,但你只需要一个。你所追求的是当你看到哨兵时看到的最后一个相关值。因此,这段代码在扫描哨兵时跟踪最后看到的值。你知道吗

代码:

marker = 2
relevant = {0, 1}
ser = [1, 2, 0, 2, 3, 1, 4, 7, 2]
d = dict()
last_found = None
for i, val in enumerate(ser):
    if val == marker:
        if last_found is not None:
            d[i] = last_found
    elif val in relevant:
        last_found = val

print(d)

结果:

{8: 1, 1: 1, 3: 0}

相关问题 更多 >