Filling 0 with previous value at index

Question:

I have a df:

           1    2   3   4   5   6   7   8   9   10

A          10   0   0   15  0   21  45  0   0   7

I am trying fill index A values with the current value if the next value is 0 so that the df would look like this:

           1    2   3   4   5   6   7   8   9   10

A          10   10  10  15  15  21  45  45  45   7

I tried:

df.loc[['A']].replace(to_replace=0, method='ffill').values

But this does not work, where is my mistake?

Asked By: Jonas Palačionis

||

Answers:

If you want to use your method, you need to work with Series on both sides:

df.loc['A'] = df.loc['A'].replace(to_replace=0, method='ffill')

Alternatively, you can mask the 0 with NaNs, and ffill the data on axis=1:

df.mask(df.eq(0)).ffill(axis=1)

output:

      1     2     3     4     5     6     7     8     9   10
A  10.0  10.0  10.0  15.0  15.0  21.0  45.0  45.0  45.0  7.0
Answered By: mozway

Well you should change your code a little bit and work with series:

import pandas as pd

df = pd.DataFrame({'1': [10], '2': [0], '3': [0], '4': [15], '5': [0],
                   '6': [21], '7': [45], '8': [0], '9': [0], '10': [7]},
                  index=['A'])
print(df.apply(lambda x: pd.Series(x.values).replace(to_replace=0, method='ffill').values, axis=1))

Output:

A    [10, 10, 10, 15, 15, 21, 45, 45, 45, 7]
dtype: object

This way, if you have multiple indices, the code still works:

import pandas as pd

df = pd.DataFrame({'1': [10, 11], '2': [0, 12], '3': [0, 0], '4': [15, 0], '5': [0, 3],
                   '6': [21, 3], '7': [45, 0], '8': [0, 4], '9': [0, 5], '10': [7, 0]},
                  index=['A', 'B'])
print(df.apply(lambda x: pd.Series(x.values).replace(to_replace=0, method='ffill').values, axis=1))

Output:

A    [10, 10, 10, 15, 15, 21, 45, 45, 45, 7]
B         [11, 12, 12, 12, 3, 3, 3, 4, 5, 5]
dtype: object
Answered By: AlirezaAsadi
df.applymap(lambda x:pd.NA if x==0 else x).fillna(method='ffill',axis=1)


   1   2   3   4   5   6   7   8   9  10
A  10  10  10  15  15  21  45  45  45   7
Answered By: G.G
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.