Set DataFrame Row/Column to 0 if it contains any string

Viewed 17

I have a dataframe in which I have some columns where I only have float values, but in some columns there is only a string (sometimes the string also contains numbers if this is relevant).

Now I'm trying to find the max value per column but I ran into some issues because of the strings. I thought it would be better anyways to remove all strings and set them to 0 as this would help working with the data afterwards.

I tried it with df.loc but I couldn't find a solution how to check if the row/column contains a string.

Could anyone push me into the right direction?

1 Answers

Assuming this input:

df = pd.DataFrame({'A': [1, 2, '3'],
                   'B': [4, 'x6', 5],
                   'C': [7, 8, 9]})

If you want to consider valid numbers:

df.apply(pd.to_numeric, errors='coerce').max()

output:

A    3.0
B    5.0
C    9.0
dtype: float64

If you want to drop all strings:

df.mask(df.applymap(lambda x: isinstance(x, str))).max()

output:

A    2
B    5
C    9
dtype: object
Related