1

I'm trying to replace a cell which contains certain string with its above cell:

Tried following code but it takes so long and cause error:

    row, col = df.shape
    for i in range(1,row):        
        if df.iloc[i,0] == "string": 
            df.iloc[i,0] = df.iloc[i-1,0]

Is there a better way to achieve this? Thanks.

0

1 Answer 1

3

The general structure for these kind of problems is df.loc[cond, col] = ...

Using @meW's setup,

df = pd.DataFrame({'col': ['Elephant', 'Grass', 'Parameter', 'Root']})
df.loc[df.col.eq('Parameter'), 'col'] = df.col.shift(1)

    col
0   Elephant
1   Grass
2   Grass
3   Root
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Vaishali, it looks good, though I used some other logic to work this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.