Was ist der beste Weg, um den letzten Nicht -Null -Wert in einem Fenster von N -Zeilen zu erhalten?
Posted: 02 May 2025, 07:03
Dies ist mein Datenrahmen: < /p>
Die erwartete Ausgabe erstellt Spalte B :
Code: Select all
df = pd.DataFrame({
'a': [0, 0, 1, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0]
})
Code: Select all
a b
0 0 0
1 0 0
2 1 0
3 -1 1
4 -1 -1
5 0 -1
6 0 -1
7 0 -1
8 0 0
9 0 0
10 -1 0
11 0 -1
12 0 -1
13 1 -1
14 0 1
< /code>
logik: < /p>
Ich erkläre die Logik anhand einiger Beispiele: < /p>
Ich möchte Spalte B für df < /p>
Ich möchte ein Fenster mit drei Zeilen mit drei Zeilen und Access -0 -Wert. Wenn alle Werte 0 sind, ist 'B' 0. In diesem Fall beträgt der letzte Nicht -Null -Wert 1. Spalte B ist also 1 < /p>
zum Beispiel für Zeilennummer 4. Der letzte Nullwert ist -1, also ist Spalte B -1 < /p>
Ich möchte dasselbe für alle Zeilen tun. < /P>
Das habe ich bisher ausprobiert. Ich denke, es muss einen besseren Weg geben. < /P>
import pandas as pd
df = pd.DataFrame({
'a': [0, 0, 1, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0]
})
def last_nonzero(x):
# x is a pandas Series representing a window
nonzero = x[x != 0]
if not nonzero.empty:
# Return the last non-zero value in the window (i.e. the one closest to the current row)
return nonzero.iloc[-1]
return 0
# Shift by 1 so that the rolling window looks only at previous rows.
# Use a window size of 3 and min_periods=1 to allow early rows.
df['b'] = df['a'].shift(1).rolling(window=3, min_periods=1).apply(last_nonzero, raw=False).astype(int)