Home > Enterprise >  How to copy value from one column to another based on conditions in pythons dataframe?
How to copy value from one column to another based on conditions in pythons dataframe?

Time:12-25

I have a dataframe image of dataftrame

I need to copy teleport_value to value column only for cases where row with column rule is 'teleport' AND column value is '', in other cases the field of column value will be without changes.

So, the data frame will be looks like: image of requested dataftrame

CodePudding user response:

Write the conditions on columns as you have described in the question and assign the output to the value. One option is to use numpy.where for such cases. Note that there are many other ways to achieve the same goal.

import numpy as np
import pandas as pd

# You don't need this part of the code, I used it to recreate the 
# dataframe, as you have shared a link to a screenshot..
df = pd.DataFrame({
    'operator': np.array([[i] * 3 for i in ['First', 'Second', 'Third']]).flatten(),
    'solution': ['row'] * 9,
    'rule': ['allow', 'block', 'teleport'] * 3,
    'value': [1, 0, '', 0, 1, 'loc', 1, 1, ''],
    'teleport_value': ['', '', 'value']   [''] * 5   ['value']
})


# Solution: I have put the comments with your own words from question,
# so that you know what does each line..
df['value'] = np.where(
    (
        (df['rule'] == 'teleport') & # row with column rule is 'teleport' AND
        (df['value'] == '') # column value is ''
    ),
    df['teleport_value'], # copy teleport_value to value column
    df['value'] # in other cases the field of column value will be without changes
)
  • Related