pandas 类型错误:无法将系列转换为 <class 'float'>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49668387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:25:18  来源:igfitidea点击:

Type error: cannot convert the series to <class 'float'>

pythonpython-3.xpandasgoogle-maps

提问by AkankshaC

      lat        long       time
 0  39.991861  116.344372   2.823611
 1  39.979768  116.310597  22.263056
 2  31.235001  121.470624  13.141667
 3  31.248822  121.460637   1.805278

The above is a dataframe rep_points. When i run the code below, it gives an error

上面是一个数据帧 rep_points。当我运行下面的代码时,它给出了一个错误

Type error: cannot convert the series to <class 'float'> 

in the line where circle is made.

在圆圈所在的那一行。

gmap = gmplot.GoogleMapPlotter(rep_points['lat'][0], rep_points['long'][0], 11)
gmap.plot(df_min.lat, df_min.lng)
gmap.scatter(rep_points['lat'],rep_points['long'],c='aquamarine')
gmap.circle(rep_points['lat'],rep_points['long'], 100, color='yellow')  
gmap.draw("user001_clus_time.html")

How should i resolve this error? Ive tried using

我应该如何解决这个错误?我试过使用

rep_pints['lat'].astype(float) 

and

rep_pints['long'].astype(float) 

but it didnt work well

但效果不佳

回答by iam.Carrot

The problem is quite trivial,

问题很简单,

  1. You're using a Pandas.DataFrame. Now when you slice it rep_points['lat'], you get a Pandas.Series.
  2. The gmplot.scatter()is expecting an iterableof floatsnot a seriesof floats.
  3. Now if you convert your Pandas.Seriesto a listby using rep_points['lat'].tolist()It'll start working
  1. 你正在使用一个Pandas.DataFrame. 现在当你切片时rep_points['lat'],你会得到一个Pandas.Series.
  2. gmplot.scatter()期待一个iterablefloats不是seriesfloats
  3. 现在,如果您通过使用将您的转换Pandas.Series为 a它将开始工作listrep_points['lat'].tolist()

Below is your updated code:

以下是您更新后的代码:

rep_points = pd.read_csv(r'C:\Users\carrot\Desktop\ss.csv', dtype=float)
latitude_collection = rep_points['lat'].tolist()
longitude_collection = rep_points['long'].tolist()

gmap = gmplot.GoogleMapPlotter(latitude_collection[0], longitude_collection[0], 11)
gmap.plot(min(latitude_collection), min(longitude_collection).lng)
gmap.scatter(latitude_collection,longitude_collection,c='aquamarine')
gmap.circle(latitude_collection,longitude_collection, 100, color='yellow')  
gmap.draw("user001_clus_time.html")

Other things that helped to point it out:

其他有助于指出这一点的事情:

  1. type(rep_points['lat'])is a Pandas.Series
  2. type(rep_points['lat'][0])is a Numpy.Float
  3. to iterate over a Pandas.Seriesyou need to use iteritems
  1. type(rep_points['lat'])是一个 Pandas.Series
  2. type(rep_points['lat'][0])是一个 Numpy.Float
  3. 迭代Pandas.Series你需要使用的iteritems