3

I'm hoping to replace values in all columns within a df using integers from a specified column. Using the df below I want to use the values in Code and replace them in all other columns.

df = pd.DataFrame({
    'Place' : ['X','Y','X','Y','X','Y','X','Y'],                                
    'Number' : ['A','B','C','D','F','G','H','I'],          
    'Code' : [1,2,3,0,1,2,5,4],    
    'Value' : ['','','','','','','','']                  
    })

df[:] = df['Code'].apply(lambda x: x if np.isreal(x) else 0).astype(int)

print(df)

Intended Output:

  Place Number  Code Value
0  1     1      1    1     
1  2     2      2    2     
2  3     3      3    3     
3  0     0      0    0     
4  1     1      1    1     
5  2     2      2    2     
6  5     5      5    5     
7  4     4      4    4

2 Answers 2

4

Use reindex, ffill, bfill

df[['Code']].reindex(columns=df.columns).ffill(1).bfill(1).astype(int)

Out[256]:
   Place  Number  Code  Value
0      1       1     1      1
1      2       2     2      2
2      3       3     3      3
3      0       0     0      0
4      1       1     1      1
5      2       2     2      2
6      5       5     5      5
7      4       4     4      4

Numpy solution

df[:] =  np.transpose([df.Code] * df.shape[1])

Out[314]:
   Place  Number  Code  Value
0      1       1     1      1
1      2       2     2      2
2      3       3     3      3
3      0       0     0      0
4      1       1     1      1
5      2       2     2      2
6      5       5     5      5
7      4       4     4      4
Sign up to request clarification or add additional context in comments.

1 Comment

@jonboy: you are welcome. Glad I could help. To make it complete, I edited the answer to add numpy solution for you :)
3

Try this:

    df[df.columns] = df[['Code', 'Code', 'Code', 'Code']]

or:

    df[df.columns] = df[['Code']*len(df.columns)]

Hope it helps.

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.