close

[Solved] Pandas/Python: Set value of one column based on value in another column

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Pandas/Python: Set value of one column based on value in another column in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Pandas/Python: Set value of one column based on value in another column Error Occurs?

Today I get the following error Pandas/Python: Set value of one column based on value in another column in python.

How To Solve Pandas/Python: Set value of one column based on value in another column Error ?

  1. How To Solve Pandas/Python: Set value of one column based on value in another column Error ?

    To Solve Pandas/Python: Set value of one column based on value in another column Error Assuming you wanted to create a new column c2, equivalent to c1 except where c1 is Value, in which case, you would like to assign it to 10:

  2. Pandas/Python: Set value of one column based on value in another column

    To Solve Pandas/Python: Set value of one column based on value in another column Error Assuming you wanted to create a new column c2, equivalent to c1 except where c1 is Value, in which case, you would like to assign it to 10:

Solution 1


one way to do this would be to use indexing with .loc.

Example

In the absence of an example dataframe, I’ll make one up here:

import numpy as np
import pandas as pd

df = pd.DataFrame({'c1': list('abcdefg')})
df.loc[5, 'c1'] = 'Value'

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5  Value
6      g

Assuming you wanted to create a new column c2, equivalent to c1 except where c1 is Value, in which case, you would like to assign it to 10:

First, you could create a new column c2, and set it to equivalent as c1, using one of the following two lines (they essentially do the same thing):

df = df.assign(c2 = df['c1'])
# OR:
df['c2'] = df['c1']

Then, find all the indices where c1 is equal to 'Value' using .loc, and assign your desired value in c2 at those indices:

df.loc[df['c1'] == 'Value', 'c2'] = 10

And you end up with this:

>>> df
      c1  c2
0      a   a
1      b   b
2      c   c
3      d   d
4      e   e
5  Value  10
6      g   g

If, as you suggested in your question, you would perhaps sometimes just want to replace the values in the column you already have, rather than create a new column, then just skip the column creation, and do the following:

df['c1'].loc[df['c1'] == 'Value'] = 10
# or:
df.loc[df['c1'] == 'Value', 'c1'] = 10

Giving you:

>>> df
      c1
0      a
1      b
2      c
3      d
4      e
5     10
6      g

Solution 2

try:

df['c2'] = df['c1'].apply(lambda x: 10 if x == 'Value' else x)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read