Home > Software engineering >  pandas new column with condition
pandas new column with condition

Time:01-01

I am having a data frame as below:

data

I need to create a new column, with the name Value-2: if the value-1 is less than 500, you need to fill the value with 0.5. if the value is less than 1000, you need to fill the value with 1.

Expected Result:

output

Can someone help me?

CodePudding user response:

I think np.where function will work efficiently on huge data as well.

import pandas as pd
import numpy as np

dictionary = {
    "Company" : ['A','A','A','A','A','A'],
    "Value1" : [480,120,876,340,996,1104]
}

dataframe = pd.DataFrame(dictionary)
dataframe["Value2"] = np.where(dataframe["Value1"] < 500, 1, 0.5)

Output:

  Company  Value1  Value2
0       A     480     0.5
1       A     120     0.5
2       A     876     1.0
3       A     340     0.5
4       A     996     1.0
5       A    1104     1.0

CodePudding user response:

Try this you can adapt the algorithm according to your needs. Here is a simple if / else.

df['Value-2'] = df['Value-1'].apply(lambda x: 0.5 if x < 500 else 1)

#  Company  Value-1  Value-2
# 0       A      480      0.5
# 1       A      120      0.5
# 2       A      876      1.0
# 3       A      340      0.5
# 4       A      996      1.0
# 5       A     1104      1.0

Using a custom function

As requested here is how to write a custom function to have more flexibility than a one-liner lambda function.

def my_fun(x):
  # can be a switch case or any complex algorithm
  return 0.5 if x < 500 else 1

df['Value-2'] = df['Value-1'].apply(my_fun)

Note

The question is not consistent on one point. It says

if value is less than 1000, need to fill the value with 1.

But the expected result shows a Value-2 = 1 for a "Value-1" higher than 1000: Value-1 = 1104.

CodePudding user response:

Please provide a working code in the future when asking questions.

import pandas as pd

Data = {
    "Company" : ['A','A','A','A','A','A'],
    "Value1" : [480,120,876,340,996,1104]
}

DataFrame1 = pd.DataFrame(Data)

DataFrame2 = []

for x in DataFrame1['Value1']:
    if x < 500 : DataFrame2.append(0.5)
    elif x < 1000 or x > 1000 : DataFrame2.append(1) # As the picture given in the question tells Value 2 is 1 when value 1 is 1104
    else : pass

DataFrame1['Value2'] = DataFrame2
print(DataFrame1)
Outputs
  Company  Value1  Value2
0       A     480     0.5
1       A     120     0.5
2       A     876     1.0
3       A     340     0.5
4       A     996     1.0
5       A    1104     1.0

  • Related