Search code examples
pythonpython-3.xpandasdata-analysis

Why it is not showing Error when I use dtype=str as argument in Series and passing data as a list of Strings and Floating point numbers.?


when I am writing code it seems like pandas Series are supporting different data types. Which concept I am missing I this code..??

This dosent shows error

import pandas as pd
d=["javeed","meera","shareef",1.12]
pd.Series(d,range(1,5),dtype=str)

This shows Error:

i=[1,2,3,4,"Javeed"]
pd.Series(i,range(1,6),dtype=int)

I expected error for both cells but it is showing error for only one cell.


Solution

  • The first one will not give you error because 1.12 will be converted to string as you mentioned dtype = str while making series.

    import pandas as pd
    d=["javeed","meera","shareef",1.12]
    sr = pd.Series(d,range(1,5),dtype=str)
    
    print(sr[4])
    print(type(sr[4]))
    

    Output:

    1.12   # this is string here
    <class 'str'>
    

    Reason: A float can be cast to string while a string can not be cast to float.

    In second series, you have strings but you are mentioning dtype = int and since strings can't be cast into int so it is giving you error.