2
$\begingroup$

In the overview page of the pandas documentation the Series data structure is described as 'homogeneously-typed'.

Data Structures
Dimensions  Name    Description
1   Series  1D labeled homogeneously-typed array
2   DataFrame   General 2D labeled, size-mutable tabular structure with potentially heterogeneously-typed column

However it is possible to create Series objects with multiple data-types.

pd.Series(data=[1,2,3,4,5,'x'], index=['a','b','c','d','e','f'])
#=>a    1
#  b    2
#  c    3
#  d    4
#  e    5
#  f    x
#  dtype: object

So what could be the meaning of homogeneously-typedmentioned in pandas documentation?

$\endgroup$
1
  • $\begingroup$ Pick one of (int, categorical, float, string). $\endgroup$
    – Emre
    Mar 22 '18 at 22:57
1
$\begingroup$

If you have multiple different types in a Series, say int and string, all of the data will get upcasted to the same dtype=object (as you can see from your example).

$\endgroup$
2
  • $\begingroup$ Is there a way to check the datatypes for all columns of a dataframe and for those columns that have multiple datatypes, list those datatypes out? $\endgroup$
    – Nick T
    Jul 1 '20 at 20:49
  • 1
    $\begingroup$ df.dtypes gives you the column type. If you want the different types for the elements in a column, you will need to iterate over the rows, e.g. using type as in junkaholik's answer. $\endgroup$
    – oW_
    Jul 1 '20 at 21:49
2
$\begingroup$

Your series is indeed homogeneously-typed and you can check it's type:

s = pd.Series(data=[1,2,3,4,5,'x'], index=['a','b','c','d','e','f'])
s.dtype
> dtype('O')

where 'O' is for "object". However, if you check the type of the individual elements of your series, they are different:

type(s['a'])
> int
type(s['f'])
> str

I think the key thing to remember is that if your Series or DataFrame Column is non homogenously-typed (eventhough technically homogeneously-typed of type "object"), then there are certain pandas functions that won't work.

Here is a better explanation from the pandas documentation's Essential Basic Functionality:

If a DataFrame or Panel contains homogeneously-typed data, the ndarray can actually be modified in-place, and the changes will be reflected in the data structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not all the same dtype), this will not be the case. The values attribute itself, unlike the axis labels, cannot be assigned to.

Note: When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.