Nate Sievers
Nate Sievers

Reputation: 1

How to create new columns base on multiple conditions in pandas?

I have a pandas dataframe with columns: First Pitch, Second Pitch, Third Pitch, and Fourth Pitch. Each column contains a pitch and it's speed.

I'm trying to make new columns based on the pitch speed. For example, there will be one column named '4 Seam Fast Ball' with the vales being the speed 91, 93 etc... another Curveball and so on.

Suggestings on how I can do this in pandas?

Data Table

Upvotes: 0

Views: 42

Answers (1)

Nate Rush
Nate Rush

Reputation: 395

There are two ways of accomplishing this, easily enough.

The first option would be to use a .apply function, in the following way:

df = pd.DataFrame({'First Pitch': [100, 200], 'Second Pitch': [300, 400]})

def calculate_new_column(row):
    return row['First Pitch'] + row['Second Pitch']

df['new_column'] = df.apply(calculate_new_column, axis=1)

The missing part from above would be splitting the string data in those columns so you can pull the numbers out of it, which is a bit trickier. You can of course do so in the same .apply function usage you see above.

Upvotes: 1

Related Questions