[英]How to override for() to get geographic coordinates from a pandas dataframe?
I have the following dataframe:我有以下 dataframe:
import pandas as pd
df = pd.DataFrame({'City': ['Paris', 'New York', 'Rio'],
'Point': [(48.853638186045075, 2.3164768734228094, 0.0),
(40.73149967161843, -73.99345738955843, 0.0),
(-22.925268779593164, -43.23729165751779, 0.0)]
})
print(df)
# Output:
City Point
Paris (48.853638186045075, 2.3164768734228094, 0.0)
New York (40.73149967161843, -73.99345738955843, 0, 0)
Rio (-22.925268779593164, -43.23729165751779, 0.0)
I need to separate the geographic coordinates from latitude and longitude.我需要将地理坐标与纬度和经度分开。 So I made the following code:所以我做了以下代码:
df['lat'] = 0
df['long'] = 0
for i in range(0, len(df)):
df['lat'].iloc[i] = df['Point'][i][0]
df['long'].iloc[i] = df['Point'][i][1]
print(df)
# Output:
City Point lat long
Paris (48.853638186045075, 2.3164768734228094, 0.0) 48.853638 2.316477
New York (40.73149967161843, -73.99345738955843, 0, 0) 40.731500 -73.993457
Rio (-22.925268779593164, -43.23729165751779, 0.0) -22.925269 -43.237292
The implementation is working perfectly.实施工作完美。 However, I would like to remove the for() to make the operation more efficient.但是,我想删除 for() 以提高操作效率。 How can I remove for()?如何删除 for()?
cols = ['lat','long']
df[cols] = df['Point'].apply(lambda p: pd.Series([p[0],p[1]]),index=cols)
Explanation: Convert each Point tuple into a Series, the result of the apply method is a DataFrame.解释:将每个Point tuple转换成一个Series,apply方法的结果是一个DataFrame。 Assign the result as new columns to df
.将结果作为新列分配给df
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.