Skip to content
Advertisement

Using np.select to change mix data types (int and str) in a Pandas column

I’ve been trying to map a column from my df into 4 categories (binning) but, the column contains mixed values in it: int and str, it looks something like this:

JavaScript

The categories I’ve been tring to change them to:

JavaScript

This has been the way I’ve been trying to solve this:

JavaScript

But, I get this error: ValueError: shape mismatch: objects cannot be broadcast to a single shape. How can I fix this? Any help is welcomed. The desired output:

JavaScript

Thank you in advance!

Advertisement

Answer

All values in your condlist for np.select must be the same length. Yours are not.


You can use pd.to_numeric with errors='coerce' to force values to convert to numeric.

Then, use pd.cut to create your bins. Convert back to strings from categorical, and replace 'nan' entries with 'text'.

Given:

JavaScript

Doing:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement