首页 > 解决方案 > 将整数变量引入数据帧时,它会被转换为浮点数。如何保持整数?

问题描述

我有一个整数变量“Sector”,当它被引入熊猫数据框时,它被转换为浮点数,但我想将它保留为整数。不知道为什么会发生。我正在使用 jupyter 笔记本。

编码:

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 

0 1.0 1.339782 103.973006
1 2.0 1.386609 103.851935
2 3.0 1.276690 103.869153
...

输出图像

如何将其保持为整数?

标签: pythondataframetypes

解决方案


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

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

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

这也有一个不幸的副作用,就是将使用的类型扩大到最窄的常见超类型,在这种情况下,float. 换句话说,sector原本是 a int,但因为latitudelongitudeare floatssector本身被扩展为 a float

如果您想避免这种情况,请改为通过在开始时list定义来收集您的值sg_sector_data = []。然后,在循环中,你可以有这个:

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

sg_sector_data.append(sector_data)

最后,最后,DataFramesg_sectors = pd.DataFrame(sg_sector_data).


推荐阅读