0
$\begingroup$

I have clustered pitchers in baseball based off of averages of advanced metrics. I am working with statcast data, so every data point is a pitch thrown as follows:

pitcher_name batter_name spin_rate release_speed release_position
derek alan 2000 90 -1.05
derek alan 2100 88 -1.03
... ... ... ... ...

To cluster pitchers, I standardized and used kmeans from sklearn to cluster based on averages of advanced metrics. The new df contains no duplicate names of pitchers, just a map from each pitcher to their respective clusters.

What I want to do is add the cluster number of each pitcher to the original dataframe. That way I can calculate batting averages based on subsets.

I was hoping to get something like this:

pitcher_name batter_name spin_rate release_speed release_position cluster
derek alan 2000 90 -1.05 0
derek phil 2100 88 -1.03 0
stevie alan 1800 94 1.09 2

Note that I have already created a cluster map, such that for any given cluster, I can find the players in that group.

Does anybody have any advice?

$\endgroup$

2 Answers 2

1
$\begingroup$

If you already have a dataframe that has the mapping between the pitcher and their cluster you can simply join this dataframe to your original dataframe using merge:

original_df.merge(cluster_mapping, on="pitcher_name")
$\endgroup$
1
  • $\begingroup$ This worked beautifully thank you! I would upvote but I just made an account so I have no karma. $\endgroup$ Mar 27, 2022 at 19:53
0
$\begingroup$

Assuming you have something like this:

from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters = n_clusters).fit(X)

You just need:

df.loc[:,"cluster"] = kmeans.labels_
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.