将Python和Nones的值转换为Pandas和Nones的值

2024-10-01 11:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列的值是float,我想把它们转换成int。在

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

它们的类型是列中的值的类型是:类“float”,除非是None类型的None。在

如果我试试这个:

^{pr2}$

我明白了:

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

如果我试试这个:

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)

我得到:

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

有人能帮忙吗?我快疯了。在


Tags: lambdanoneid类型cityifobjectnot
1条回答
网友
1楼 · 发布于 2024-10-01 11:26:31

我认为在熊猫中,不能在同一列中有int和None或nan。它还不支持。在

如果可以将“无”转换为0,可以执行以下操作:

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

相关问题 更多 >