0

I can't add insert mean values instead of zeros in a DataFrame table column.

I have a single table DataFrame - which is a single column.

I'm trying to remove the zeros from this column - and replace them with the nearest values - that are nearby.

Is it possible to come up with something similar?

I thought for a long time but could not come up with anything.

I would be very grateful for any information.


i = 2
for i in range(len(df)):
    if df.loc[i, "t"] != 0 and df.loc[i-3, "t"] != 0:
        df.at[i-2, "t"] = df.at[i-3, "t"]
        df.at[i-1, "t"] = df.at[i, "t"]
    i = i + 1

    i = 0
    for i in range(len(df)):
        if df.loc[i, "t"] == 0 and i < (len(df)-1):
            if df.loc[i+1, "t"] != 0:
                df.at[i, "t"] = df.at[i+1, "t"]
        elif df.loc[i, "t"] == 0 and df.loc[i+3, "t"] == 0 and i < (len(df)-1):
            if df.loc[i-1, "t"] != 0:
                df.at[i, "t"] = df.at[i-1, "t"]
        i = i + 1

0
0
-1.2
0
0
-3.5
0
0
1.59
0
0
2.93
0
0
-4.7
0
0
4.36
0
0
2.18
0

--

-1.2
-1.2
-1.2
-1.2
-3.5
-3.5
-3.5
1.59
1.59
1.59
2.93
2.93
2.93
-4.7
-4.7
-4.7
4.36
4.36
4.36
2.18
2.18
2.18

--

-1.2
-1.2
-1.2 = (-1.2 + -3.5) / 2
-1.2 = (-1.2 + -3.5) / 2
-3.5
-3.5 = (-3.5 + 1.59) / 2
-3.5 = (-3.5 + 1.59) / 2
1.59
1.59
1.59
2.93
2.93
2.93
-4.7
-4.7
-4.7
4.36
4.36
4.36
2.18
2.18
2.18
Cristensen
  • 75
  • 6
  • 1
    Does this answer your question? [Pandas missing values : fill with the closest non NaN value](https://stackoverflow.com/questions/44782881/pandas-missing-values-fill-with-the-closest-non-nan-value) – Franciska Feb 13 '23 at 21:52

1 Answers1

0

You can use something like this: First, fill zeros with nan.

df['col']=df['col'].replace(0,np.nan)

then use fillna() with method parameter:

df['col']=df['col'].fillna(method='ffill') #'backfill', 'bfill', 'pad', 'ffill'

or use interpolate():

df['col']=df['col'].interpolate(method='nearest')
Bushmaster
  • 4,196
  • 3
  • 8
  • 28