3

I have a csv file that contains longitude, latitude and other data. Use pd.read_csv read data then put longitude and latitude into a dataframe. Defined a new DF: longLat = gps[["Longitude", "Latitude"]] tried longLat = longLat.apply(pd.to_numeric, errors='raise'), but not working

Error message: AttributeError: 'Series' object has no attribute 'radians'.

Here are what I have tried:

data1 = pd.read_csv("xxx.csv",index_col = False)
# data1 = data1.apply(pd.to_numeric, errors='ignore')

timestamps = data1["time"]
latitude = data1["latitude"]
longitude = data1["longitude"]
travelstate = data1["travelstate"]

month = []
day = []
hour = []
weekday= []
timestamps.head()
data1.head()
for timestamp in timestamps:
        month.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%m'))
        day.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%d'))
        hour.append(datetime.utcfromtimestamp(float(timestamp)).strftime('%H'))
        weekday.append((pd.to_datetime(timestamp, unit = "s").weekday()))

gps = pd.DataFrame(columns = ["Month","Day","Hour","Weekday","Longitude","Latitude","Travel State"])
gps["Month"] = month
gps["Day"] = day
gps["Hour"] = hour
gps["Weekday"] =weekday
gps["Longitude"] = longitude
gps["Latitude"] = latitude
gps["Travel State"] = travelstate

longLat = gps[["Longitude", "Latitude"]]

def haversine(lat1, lon1, lat2, lon2, to_radians= True,
    earth_radius=6371):
        if to_radians:
            lat1, lon1, lat2, lon2 = numpy.radians([lat1, lon1, lat2, lon2])

        a = np.sin((lat2-lat1)/2.0)**2 + \
            np.cos(lat1) * np.cos(lat2) * numpy.sin((lon2-lon1)/2.0)**2

        return earth_radius * 2 * np.arcsin(np.sqrt(a))

a = haversine(longLat.Longitude.shift(), longLat.Latitude.shift(),
    longLat.loc[1:,"Longitude"], longLat.loc[1:,"Latitude"])

print(a)
wwwslinger
  • 936
  • 8
  • 14
Katrina
  • 274
  • 1
  • 2
  • 13
  • Why do you have references to both `numpy` and `np`? Did you assign a `Series` to `numpy`? – gmds Apr 08 '19 at 22:34
  • i was just trying different things. You were right, it should be np bc i import numpy as np.. No, I didnt assign it to numpy. Should I do that? – Katrina Apr 08 '19 at 22:38
  • No, that would be bad. However, I see nothing in your code that would cause that error, except for `numpy.radians`, which would most likely only do that if `numpy` was a `Series` (because that's the error that would be raised by trying to access a nonexistent `radians` attribute of a `Series`). Is there any other relevant code? – gmds Apr 08 '19 at 22:41
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. h4tuna We should be able to paste your posted code into a text file and reproduce the problem you described. – Prune Apr 08 '19 at 22:43
  • I have updated everything I wrote... Thank you @gmds – Katrina Apr 08 '19 at 22:51

2 Answers2

3
gps['p_latitude'] = gps['Latitude'].shift(1)
gps['p_longitude'] = gps['Longitude'].shift(1)


distanceI = gps[['p_latitude', 'p_longitude', 'Latitude','Longitude']].apply(lambda x: haversine(x[1], x[0], x[3], x[2]), axis=1)

This works a great solution except you have to interchange haversine(x[1], x[0], x[3], x[2]), axis=1) to apply(lambda x: haversine(x[0], x[1], x[2], x[3]), axis=1)

Kamanda_K
  • 3
  • 2
Katrina
  • 274
  • 1
  • 2
  • 13
2

Should not use longLat in:

 a = haversine(longLat.Longitude.shift(),longLat.Latitude.shift(),
    longLat.loc[1:,"Longitude"], longLat.loc[1:"Latitude"])

It works when use:

a =  haversine_np(gps.Longitude.shift(), gps.Latitude.shift(),
                 gps.loc[1:, 'Longitude'], gps.loc[1:, 'Latitude'])
Katrina
  • 274
  • 1
  • 2
  • 13