pandas中DataFrame新增行及global變量的使用方式
pandas DataFrame新增行及global變量使用
Global變量
在函數(shù)體或類外定義的變量,若想在函數(shù)體或類中使用,必須先聲明使用的是體外global變量
聲明格式:global 變量名
import pandas as pd import numpy as np import math #global變量 df_result=pd.DataFrame(columns=['LABELS','DISTANCE']) #計算距離 def dist(x): # 計算兩點經(jīng)緯度的火星坐標系距離 global df_result #使用全局變量 pa=[0,0] pb=[0,0] pa[0]=x["LNG"] pa[1]=x["LAT"] pb[0]=x["LNG_LAST"] pb[1]=x["LAT_LAST"] label=x["LABELS"] #計算pa、pb之間經(jīng)緯度距離 b =math.pi/ 180 c =math.sin((float(pb[1]) - float(pa[1])) * b / 2) d =math.sin((float(pb[0]) - float(pa[0])) * b / 2) a = c * c + d * d * math.cos(float(pa[1]) * b) * math.cos(float(pb[1]) * b) dis=int(12756274 * math.atan2(math.sqrt(a), math.sqrt(1 - a))) tmp=pd.DataFrame({"LABELS":label, "DISTANCE":dis},index=[0]) #向DataFrame對象新增行 df_result=df_result.append(tmp,ignore_index=True)
geopandas與pandas
geopandas是基于pandas的邏輯開發(fā)的能夠處理矢量數(shù)據(jù)的python庫(是否能夠處理柵格不太確定)那他與pandas的關系如何呢 用一個例子測試一下
1.載入測試數(shù)據(jù)
import geopandas as gpd import matplotlib.pyplot as plt icosa =gpd.read_file('./icosa.shp') icosa1 =gpd.read_file('./icosaPoint.shp')
2.測試geopandas的merge.與pandas的merge函數(shù)相似
但是有一點區(qū)別
pdJoinData =icosa.merge(icosa1,on='global_id') print(type(pdJoinData)) 輸出:<class 'pandas.core.frame.DataFrame'>
官方文檔:
Attribute joins are accomplished using the merge
method. In general, it is recommended to use the merge
method called from the spatial dataset. With that said, the stand-alone merge
function will work if the GeoDataFrame is in the left
argument; if a DataFrame is in the left
argument and a GeoDataFrame is in the right
position, the result will no longer be a GeoDataFrame.
屬性連接是使用該merge
方法完成的。一般情況下,建議使用merge
從空間數(shù)據(jù)集調(diào)用的方法。
話雖如此,merge
如果 GeoDataFrame 在left
參數(shù)中,獨立函數(shù)將起作用;如果 DataFrame 在left
參數(shù)中并且 GeoDataFrame 在right
位置,結果將不再是 GeoDataFrame。
也就是所這個合并方法如果dataframe調(diào)用的,那么返回的是dataframe (pandas的數(shù)據(jù)結構)如果是GeoDataFrame 調(diào)用 并且右參數(shù)是dataframe類型那么返回的是GeoDataFrame類型
還有一種情況官方?jīng)]有說 兩個GeoDataFrame調(diào)用屬性合并merge得到什么?
如上圖得到的是pandas的DataFrame 而且里面存儲了兩個shp的geometry 也就是存儲了兩個geoserise
通過構造函數(shù)能把這個DataFrame轉化為geoDataFrame 需要指定geometry,現(xiàn)在gdf就是geodataframe了。
和普通的相比,它有多列GeoSeries
只有最后一列 geometry代表的空間。
而且不能輸出為地理格式 因為geometry不能作為屬性輸出 但是可以to_csv
gdf = geopandas.GeoDataFrame(pdJoinData, geometry=pdJoinData['geometry_y'])
綜上,pandas和geopandas的數(shù)據(jù)類型是完全一樣的 pandas也可以包含GeoSeries
但是geopandas要包含一個默認的geometry 代表地理空間位置
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python文件遍歷os.walk()與os.listdir()使用及說明
這篇文章主要介紹了Python文件遍歷os.walk()與os.listdir()使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11Python深度學習pytorch神經(jīng)網(wǎng)絡匯聚層理解
通常當我們處理圖像時,我們希望逐漸降低隱藏表示的空間分辨率,聚集信息,這樣隨著我們在神經(jīng)網(wǎng)絡層疊的上升,每個神經(jīng)元對其敏感的感受野(輸入)就越大2021-10-10Python?pygame派生精靈和精靈組創(chuàng)建敵機
這篇文章主要為大家介紹了Python?pygame派生精靈和精靈組創(chuàng)建敵機示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08