Pandas copy value from another column if condition

Copying values from another column based on a condition using pandas

In pandas, you can copy values from one column to another column based on a certain condition using the `loc` method.

Let’s say we have a dataframe called `df` with two columns – `column1` and `column2`. We want to copy values from `column1` to `column2` if a certain condition is met.

  1. First, let’s import the necessary libraries:
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/pandas/1.1.5/pandas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  3. Next, create a dataframe `df`:
  4. <script>
        var df = new pandas.DataFrame({
            'column1': [10, 15, 20, 25, 30],
            'column2': [100, 200, 300, 400, 500]
        });
    </script>
  5. Use the `loc` method to copy values from `column1` to `column2` based on a condition:
  6. <script>
        df.loc[df['column2'] < 300, 'column2'] = df['column1'];
    </script>

    In this example, we copy the values from `column1` to `column2` only if the value in `column2` is less than 300. The `loc` method allows us to select rows based on conditions and modify specific columns.

  7. Finally, print the updated dataframe:
  8. <script>
        console.log(df.to_string());
    </script>

    By logging the dataframe to the console, you will see the updated values in `column2`:

    
          column1  column2
        0       10       10
        1       15       15
        2       20       20
        3       25      400
        4       30      500
            

Leave a comment