将整型变量引入数据帧时,整型变量将转换为float。如何将其保持为整数?

2024-05-13 16:48:55 发布

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

我有一个整数变量“Sector”,当它被引入pandas数据帧时,它会被转换成float,但我想将它保持为整数。不知道为什么会这样。我在一本笔记本上工作

守则:

sector=0
last_sector=1
for sector in range(last_sector,83):
    try:
        address = 'Singapore'+', '+str(sector)
        geolocator = Nominatim(user_agent="to_explorer")
        location = geolocator.geocode(address)
        latitude = location.latitude
        longitude = location.longitude
        print('The geographical coordinates for {} are {}, {}.'.format(address,latitude, longitude))
        sg_sectors = sg_sectors.append({'Sector': sector,
                                        'Latitude': latitude,
                                        'Longitude': longitude}, ignore_index=True)
    except:
        last_sector=int(sg_sectors['Sector'].max())
        print('Coordinates for sectors up to ',last_sector,' have already been gathered')

输出为:

 Sector   Latitude  Longitude 

01.01.339782 103.973006
1 2.0 1.386609 103.851935
23.0 1.276690 103.869153
...

image of the output

如何将其保持为整数


Tags: toforaddresslocation整数sglastprint
2条回答

原因是这一行是pandas反模式:

sg_sectors = sg_sectors.append({'Sector': sector,
                                'Latitude': latitude,
                                'Longitude': longitude}, ignore_index=True)

每次迭代都要创建一个新的DataFrame。在这种特定情况下,这可能无关紧要,因为您的数据集相对较小,但如果您放大,它会。很多

这还有一个不幸的副作用,那就是将使用的类型扩展到最窄的通用超类型,在本例中是float。换句话说,sector最初是一个int,但因为latitudelongitudefloats,所以sector本身被扩大为一个float

如果要避免这种情况,请在list中收集值,例如在开始时定义sg_sector_data = []。然后,在循环中,您可以有:

sector_data = {'Sector': sector, 'Latitude': latitude, 'Longitude': longitude}

sg_sector_data.append(sector_data)

最后,在最后,用sg_sectors = pd.DataFrame(sg_sector_data)创建你的DataFrame

通过应用astype,可以将列设置为特定的数据类型

df= pd.DataFrame(np.arange(5), columns=['a'])
df.a = df.a.astype(float)
print(df)
     a
0  0.0
1  1.0
2  2.0
3  3.0
4  4.0
df = df.astype({'a':int})
print(df)
   a
0  0
1  1
2  2
3  3
4  4

您可以像我在第一篇文章中所做的那样,将此数据类型应用于所有列,创建一个浮点数据帧,但也可以将效果限制在某些列上,使用字典将该列再次设置为整数

希望,这会有帮助。最好的,莱帕克

相关问题 更多 >