Why np.mean applied to a pandas string column does not yield an error?

Viewed 212

How does the logic of calculating a mean on a string column work (the result is 246.8)? Is there any specific use case for it?

import pandas as pd
import numpy as np

s = np.array(["0", "1", "2", "3", "4"])
pd.DataFrame(s).mean()

Out[1]: 
0    246.8
dtype: float64

Just to be clear, I am aware that to calculate the mean of numbers, I should do something along these lines.

pd.DataFrame(s.astype(int)).mean()

Out[2]: 
0    2.0
dtype: float64
1 Answers

What is happening is that the strings are getting concatenated (which is the addition of strings), forming the string "01234", which gets cast into the number 1234, then, 1234 / 5 = 246.8. This will only happen if the strings are numerical, i.e. they represent numbers in a string format, try adding a non-numerical string (e.g. "x" or "hello") to the list and you will see that it will not work.

Related