0

Probably a rookie question, but I'm new to Python and Pandas and still learning the syntax. I'm developing a script where I'd like to structure a conditional that multiplies a cell value over an entire column.

Here's the structure of the test.csv:

enter image description here

I'd like to create a column error_count_score that multiplies the value in the error_count cell by 3 if it is greater than 3 (as an Excel formula, it would be: =IF(C2<=3,0,(C2*3)) ). The values for the new column in this case would be 0 and 12.

I suspect there are multiple ways to solve this, but I'm uncertain how to structure the code. Here's my working code attempt:

import pandas as pd

df = pd.read_csv("test.csv")
    
df.loc[df['error_count'] >= 3, 'error_count_score'] = #do I put an object here? * 3

Any assistance or advice greatly appreciated.

1 Answer 1

1

You can create a function that does exactly what you want for a single element in the column, and then apply that function over every element of the column, generating your new column.

This is done via the DataFrame.apply method.

In your case:

def my_function(element):
    if element <= 3:
        return 0
    else: 
        return element * 3

df['error_count_score'] = df['error_count'].apply(my_function)

Note that pandas expects my_function to take an argument (each element of a column), and then apply it through some logic, returning a new element in the end. This is exactly what's happening here.

As you get used to pandas, you'll see that a lot of times people don't bother defining a function just to apply it a single time. In these cases, people will use an anonymous function - basically a function that only exists for one line - using the lambda keyword.

In your case:

df['error_count_score'] = df['error_count'].apply(lambda element: 0 if element <= 3 else element * 3)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.