0

Given the following df:

df_test = pd.DataFrame({'0' : ['find expert model','NR','R','NR'],
               '1' : ["news recommend", "NR" ,"NR", "NR"],
               '2' : ["a recommend", "R" , "NR", "NR"],
               '3' : ["a web recommend", "R", "NR", "R"]})
df_test

    0                   1               2           3
0   find expert model   news recommend  a recommend a web recommend
1   NR                  NR              R           R
2   R                   NR              NR          NR
3   NR                  NR              NR          R

I am trying to obtain this form of the df:

    0                   1               2           3
0   NR                  NR              a recommend a web recommend
1   find expert model   NR              NR          NR
2   NR                  NR              NR          a web recommend

The goal here is to replace every string R in a certain cell with the string from the first row of the distinct column. The replacing process should begin at the row with index 1.

Any ideas? Thanks in advance!

1
  • can you be more explicit in what you're trying to achieve? Commented Jul 25, 2019 at 19:16

2 Answers 2

3

Try this using apply, replace, and drop:

df_test.apply(lambda x: x.replace('R', x.iloc[0])).drop(0).reset_index(drop=True)

Output:

                   0   1            2                3
0                 NR  NR  a recommend  a web recommend
1  find expert model  NR           NR               NR
2                 NR  NR           NR  a web recommend
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

for col in df.columns:
    df.loc[df[col] == 'R', col] = df.loc[0, col]
df = df.drop(0)
df.reset_index(drop=True, inplace=True)

Results in:

                   0               1            2                3
0                 NR              NR  a recommend  a web recommend
1  find expert model              NR           NR               NR
2                 NR              NR           NR  a web recommend

Comments

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.