python - 将整数变量引入数据帧时,它会被转换为浮点数。如何保持整数?
问题描述
我有一个整数变量“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
...
如何将其保持为整数?
解决方案
原因是这一行,这是一个pandas
反模式:
sg_sectors = sg_sectors.append({'Sector': sector,
'Latitude': latitude,
'Longitude': longitude}, ignore_index=True)
您正在创建一个新 DataFrame
的每次迭代。在这种特定情况下,这可能无关紧要,因为您的数据集相对较小,但如果您扩大规模,它会。很多。
这也有一个不幸的副作用,就是将使用的类型扩大到最窄的常见超类型,在这种情况下,float
. 换句话说,sector
原本是 a int
,但因为latitude
和longitude
are floats
,sector
本身被扩展为 a float
。
如果您想避免这种情况,请改为通过在开始时list
定义来收集您的值sg_sector_data = []
。然后,在循环中,你可以有这个:
sector_data = {'Sector': sector, 'Latitude': latitude, 'Longitude': longitude}
sg_sector_data.append(sector_data)
最后,最后,DataFrame
用sg_sectors = pd.DataFrame(sg_sector_data)
.
推荐阅读
- java - Android 向我发送两次相同的消息
- swiftui - 我的选择如何正确地出现在我在 SwiftUI 中创建的列表中
- python - “浮动”对象不是 iretable 错误;但我没有看到我在迭代什么?
- javascript - 为什么我的页面在 onChange 触发器更新后重新加载?
- ios - 在 MacCatalyst 的 SwiftUI 应用程序中隐藏标题栏
- assembly - 2D Arrays 并在 Assembly 中将它们添加到一起
- javascript - 循环遍历 Java Script 中的构造函数
- php - 未捕获的语法错误:意外的令牌 '<' - Homestead
- html - xQuery 为什么我在使用 normalize-space 函数时仍然得到空格?
- powershell - 将 Sharepoint 文件夹(但不是实际文件夹)的内容复制到同一站点的目录中