我有一个整数变量“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
...
如何将其保持为整数
原因是这一行是
pandas
反模式:每次迭代都要创建一个新的
DataFrame
。在这种特定情况下,这可能无关紧要,因为您的数据集相对较小,但如果您放大,它会。很多这还有一个不幸的副作用,那就是将使用的类型扩展到最窄的通用超类型,在本例中是
float
。换句话说,sector
最初是一个int
,但因为latitude
和longitude
是floats
,所以sector
本身被扩大为一个float
如果要避免这种情况,请在
list
中收集值,例如在开始时定义sg_sector_data = []
。然后,在循环中,您可以有:最后,在最后,用
sg_sectors = pd.DataFrame(sg_sector_data)
创建你的DataFrame
通过应用astype,可以将列设置为特定的数据类型
您可以像我在第一篇文章中所做的那样,将此数据类型应用于所有列,创建一个浮点数据帧,但也可以将效果限制在某些列上,使用字典将该列再次设置为整数
希望,这会有帮助。最好的,莱帕克
相关问题 更多 >
编程相关推荐