Home > other >  Replace elements of a dataframe with a values at another dataframe elements
Replace elements of a dataframe with a values at another dataframe elements

Time:06-14

I want to replace df2 elements with df1 elements but according to that: If df2 first row first column has value '1' than df1 first row first column element is getting there, If it is zero than '0' stands. If df2 any row last column element is '1' than df1 that row last column element is coming there. It is going to be like that.

enter image description here

enter image description here

So i want to replace all df2 '1' element with df1 elements according to that rule. df3 is going to be like:

abcde0000; abcd0e000; abcd00e00;...

CodePudding user response:

We can use apply function for this. But first you have concat both frames along axis 1. I am using a dummy table with just three entries. It can be applied for any number of rows.

import pandas as pd
import numpy as np

# Dummy data
df1 = pd.DataFrame([['a','b','c','d','e'],['a','b','c','d','e'],['a','b','c','d','e']])
df2 = pd.DataFrame([[1,1,1,1,1,0,0,0,0],[1,1,1,1,0,1,0,0,0],[1,1,1,1,0,0,1,0,0]])

# Display dataframe . May not work in python scripts. I used them in jupyter notebooks
display(df1)
display(df2)

# Concat DFs
df3 = pd.concat([df1,df2],axis=1)
display(df3)

# Define function for replacing
def replace(letters,indexes):
    seek =0
    for i in range(len(indexes)):
        if indexes[i]==1:
            indexes[i]=letters[seek]
            seek =1
    return ''.join(list(map(str,indexes)))

# Applying replace function to dataframe
df4 = df3.apply(lambda x: replace(x[:5],x[5:]),axis=1)

# Display df4
display(df4)

The result is

0    abcde0000
1    abcd0e000
2    abcd00e00
dtype: object

I think this will solve your problem

  • Related