Sum ignoring strings in pandas dataframe

Viewed 2194

I am using Pandas to make a DataFrame. However some parts of the DataFrame contain a string. how can I ignore these strings in the sum when summing along the rows of the data frame?

df["sum"] = df.sum(axis=1)
2 Answers

Use the numeric_only flag:

df.sum(axis=1, numeric_only=True)

If you want to ignore the string values, then this will work:

for col in df.columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
df['sum'] = df.sum(axis=1)
Related