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.

1
  • 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 Commented Jun 27, 2017 at 21:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.