1
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print df

When create DataFrame, we define the data type to be float, but not named which column to change to float. We leave it to python to decide if it makes sense to change the column data type or not, based on the value.

Just wondering, on this practice, is this still strict strongly typed?

Thanks!

searain
  • 3,143
  • 6
  • 28
  • 60

1 Answers1

3

Python is a strongly, dynamically typed language (see Is Python strongly typed?).

If you pass dtype=float explicitly when constructing a pd.DataFrame, Pandas will try to coerce all columns to float. In your case, the 'Name' column cannot be coerced to float, so it will remain as object (you can think of this as str in pure Python).

In general, you can leave dtype blank to have Pandas infer datatypes for DataFrames. Then do a df.info() to see if dtypes make sense to you. The ones you don't approve, you can change them like so:

df['Age'] = df['Age'].astype(int)
mellifluous
  • 173
  • 2
  • 8
  • 3
    To add to this, python _itself_ is strongly typed, which means it will never automatically perform type coercion. But Pandas is a library which explicitly provides type coercion. – Hamms Jul 12 '18 at 20:49