Updated answer, April 2025:
pd.to_numeric can convert arguments to a numeric type. The option errors='coerce' sets things to NaN. However, it can only work on 1D objects (i.e. scalar, list, tuple, 1-d array, or Series). Therefore, to use it on a DataFrame, we need to use df.apply to convert each column individually. Note that any **kwargs given to apply will be passed onto the function, so we can still set errors='coerce'.
Using pd.to_numeric along with df.apply will set any strings to NaN. If we want to convert those to 0 values, we can then use .fillna(0) on the resulting DataFrame.
For example (and note this also works with the strings suggested by the original question "$-" and "($24)"):
import pandas as pd
df = pd.DataFrame({
'a': (1, 'sd', 1),
'b': (2., 2., 'fg'),
'c': (4, "$-", "($24)")
})
print(df)
# a b c
# 0 1 2.0 4
# 1 sd 2.0 $-
# 2 1 fg ($24)
df = df.apply(pd.to_numeric, errors='coerce').fillna(0)
print(df)
# a b c
# 0 1.0 2.0 4.0
# 1 0.0 2.0 0.0
# 2 1.0 0.0 0.0
My original answer from 2015, which is now deprecated
You can use the convert_objects method of the DataFrame, with convert_numeric=True to change the strings to NaNs
From the docs:
convert_numeric:
If True, attempt to coerce to numbers (including strings), with unconvertible values becoming NaN.
In [17]: df
Out[17]:
a b c
0 1. 2. 4
1 sd 2. 4
2 1. fg 5
In [18]: df2 = df.convert_objects(convert_numeric=True)
In [19]: df2
Out[19]:
a b c
0 1 2 4
1 NaN 2 4
2 1 NaN 5
Finally, if you want to convert those NaNs to 0's, you can use df.replace
In [20]: df2.replace('NaN',0)
Out[20]:
a b c
0 1 2 4
1 0 2 4
2 1 0 5