0

I have a column with values in floats and I want to turn them into ints.

pdsm:
    federation_unit_id  city_id
id                             
3                  8.0      3.0
7                 None     None
17                 8.0      3.0
18                 8.0      3.0
19                 8.0      9.0

Their types are of values in the columns are: class 'float', except by None that is a NoneType.

If I try this:

pdsm['federation_unit_id']=pdsm['federation_unit_id'].astype(int)
pdsm['city_id'].iloc[0]=pdsm.city_id.astype(int)

I get this:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

If I try this:

pdsm['federation_unit_id']=pdsm['federation_unit_id'].apply(lambda x: x.astype(int) if x is not None else None)
pdsm['city_id'].iloc[0]=pdsm.city_id.apply(lambda x: x.astype(int) if x is not None else None)

I get:

AttributeError: 'float' object has no attribute 'astype'

Can anyone help? I'm going nuts here.

aabujamra
  • 4,494
  • 13
  • 51
  • 101
  • 2
    You cannot have a column with missing values as type int. Unfortunately there is no missing value for the int data types. It must be float. This will be fixed in pandas 2.0 – Ted Petrou Jun 27 '17 at 21:23

1 Answers1

6

I think in pandas you can't have int and None or nan in the same column. Its' not supported yet.

If you are ok with converting None to 0, you can do:

df.fillna(0).astype(int)
Out[157]: 
    federation_unit_id  city_id
id                             
3                    8        3
7                    0        0
17                   8        3
18                   8        3
19                   8        9
Allen Qin
  • 19,507
  • 8
  • 51
  • 67