Data Types and Pandas

What are the data types admitted in a Pandas object?

Question: What are the data types admitted in a Pandas object?

Answer: Mainly, Pandas uses NumPy arrays as the concrete objects contained with an Index, Series, or DataFrame. To recall the various NumPy dtypes, please refer to the sections on NumPy arrays.

Can a Series contain multiple data types?

Question: Can a Series contain multiple data types?

Answer: Yes, a Series can contain multiple data types (hence, a DataFrame can). In this sense, Pandas offers a more flexible data structure than NumPy arrays, which must contain objects of the same type. The code snippet below shows that a list with mixed types is downgraded to a NumPy array with string objects. Instead, a Series preserves the type of each object (see line 22).

# import numpy and pandas with the socially accepted alias 'np' and 'pd'
>>> import numpy as np
>>> import pandas as pd

# a list with a string, a float, and an integer
>>> L = ["xyz", -17.64, 0]

# create a NumPy array from the list
>>> A = np.array(L)
>>> print(A)
['xyz' '-17.64' '0']

# create a Series from the list
>>> S = pd.Series(L)
>>> print(S)
0      xyz
1   -17.64
2        0
dtype: object

# proof that Series preserves the type of the individual object
# --+ fetch the second item of the list and carry out a mathematical operation
>>> S[1]/2
-8.82