簡體   English   中英

如何根據 Pandas 中現有列的計算創建新列?

[英]How to create a new column based on calculation done with the existing column in Pandas?

將haversine導入為hs

輸入數據具有客戶密碼和分支密碼的緯度和經度。

輸入:

Customer_lat_lon     | branch_lat_lon|
(28.682,77.175)       (28.599,77.334)
(19.126,72.865)       (19.104,72.863)

我正在創建一個 function 來計算兩列之間的距離。

def calc_distance:
  try:
    return hs.haversine(x,y)
  except:
     return np.nan

現在我需要一個新列作為距離,它在 function 的幫助下計算兩列之間的距離。

例子:

calc_distance(df['Customer_lat_lon'][0],df[branch_lat_lon][0])

給我一個 18.0612 的結果

如何對所有記錄執行此操作。 我有 1000 條需要計算距離的記錄。

預期 output:

Customer_lat_lon     | branch_lat_lon| distance 
(28.682,77.175)       (28.599,77.334) | 18.0612

使用df.apply()沿軸應用 function。

import numpy as np
import pandas as pd
from haversine import haversine


def calc_distance(s):
    try:
        return haversine(s.customer_lat_lon, s.branch_lat_lon)
    except Exception:
        return np.nan


df = pd.DataFrame(
    {
        "customer_lat_lon": [(28.682, 77.175), (19.126, 72.865)],
        "branch_lat_lon": [(28.599, 77.334), (19.104, 72.863)],
    }
)

df["Distance"] = df.apply(calc_distance, axis=1)
print(df)
   customer_lat_lon    branch_lat_lon   Distance
0  (28.682, 77.175)  (28.599, 77.334)  18.054029
1  (19.126, 72.865)  (19.104, 72.863)   2.455300

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM