第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

加速熊貓中的雙 iterrows()

加速熊貓中的雙 iterrows()

守候你守候我 2022-05-24 17:07:31
我有幾個需要用 pandas 處理的大型數(shù)據(jù)集(約 3000 行,100 列)。每行代表地圖上的一個點,并且有一堆與該點相關的數(shù)據(jù)。我正在做空間計算(將來可能會引入更多變量),所以對于每一行我只使用來自 1-4 列的數(shù)據(jù)。問題是我必須將每一行與其他每一行進行比較——本質(zhì)上,我試圖找出每個點之間的空間關系。在項目的這個階段,我正在計算以確定表中每個點的給定半徑內(nèi)有多少點。我必須這樣做 5 或 6 次(即運行多個半徑大小的距離計算功能。)這意味著我最終需要進行大約 10-50 百萬次計算。它很慢。非常慢(比如 9+ 小時的計算時間。)運行所有這些計算后,我需要將它們作為新列附加到原始(非常大)數(shù)據(jù)框中。目前,我一直在將整個數(shù)據(jù)框傳遞給我的函數(shù),這可能會進一步減慢速度。我知道很多人在超級計算機或?qū)S枚嗪藛卧线\行這種規(guī)模的計算,但我想盡我所能優(yōu)化我的代碼以盡可能高效地運行,而不管硬件如何。我目前正在使用帶有 .iterrows() 的雙 for 循環(huán)。我已經(jīng)盡可能多地去掉了不必要的步驟。我可以將數(shù)據(jù)幀配對成一個子集,然后將其傳遞給函數(shù),并在另一個步驟中將計算附加到原始數(shù)據(jù),如果這有助于加快速度的話。我還考慮過使用 .apply() 來消除外部循環(huán)(例如 .apply() 內(nèi)部循環(huán)到數(shù)據(jù)幀中的所有行......?)下面,我展示了我正在使用的功能。這可能是我為這個項目所擁有的最簡單的應用程序......還有其他人根據(jù)某些空間標準進行更多計算/返回對或點組,但這是展示我的基本概念的最佳示例正在做。# specify file to be read into pandasdf = pd.read_csv('input_file.csv', low_memory = False)# function to return distance between two points w/ (x,y) coordinatesdef xy_distance_calc(x1, x2, y1, y2):    return math.sqrt((x1 - x2)**2 + (y1-y2)**2)# function to calculate number of points inside a given radius for each pointdef spacing_calc(data, rad_crit, col_x, col_y):    count_list = list()    df_list = pd.DataFrame()    for index, row in data.iterrows():        x_row_current = row[col_x]        y_row_current = row[col_y]        count = 0        # dist_list = list()        for index1, row1 in data.iterrows():            x1 = row1[col_x]            y1 = row1[col_y]            dist = xy_distance_calc(x_row_current, x1, y_row_current, y1)            if dist < rad_crit:                 count += 1            else:                continue        count_list.append(count)    df_list = pd.DataFrame(data=count_list, columns = [str(rad_crit) + ' radius'])    return df_list# call the function for each radius in question, append new datadf_2640 = spacing_calc(df, 2640.0, 'MID_X', 'MID_Y')df = df.join(df_2640)df_1320 = spacing_calc(df, 1320.0, 'MID_X', 'MID_Y')df = df.join(df_1320)沒有錯誤,一切正常,我只是不認為它盡可能高效。
查看完整描述

1 回答

?
婷婷同學_

TA貢獻1844條經(jīng)驗 獲得超8個贊

你的問題是你循環(huán)太多次。至少,您應該計算一個距離矩陣并計算有多少點落在該矩陣的半徑內(nèi)。但是,最快的解決方案是使用 numpy 的向量化函數(shù),它們是高度優(yōu)化的 C 代碼。


與大多數(shù)學習經(jīng)驗一樣,最好從一個小問題開始:


>>> import numpy as np

>>> import pandas as pd

>>> from scipy.spatial import distance_matrix


# Create a dataframe with columns two MID_X and MID_Y assigned at random

>>> np.random.seed(42)

>>> df = pd.DataFrame(np.random.uniform(1, 10, size=(5, 2)), columns=['MID_X', 'MID_Y'])

>>> df.index.name = 'PointID'


            MID_X     MID_Y

PointID                    

0        4.370861  9.556429

1        7.587945  6.387926

2        2.404168  2.403951

3        1.522753  8.795585

4        6.410035  7.372653


# Calculate the distance matrix

>>> cols = ['MID_X', 'MID_Y']

>>> d = distance_matrix(df[cols].values, df[cols].values)


array([[0.        , 4.51542241, 7.41793942, 2.94798323, 2.98782637],

        [4.51542241, 0.        , 6.53786001, 6.52559479, 1.53530446],

        [7.41793942, 6.53786001, 0.        , 6.4521226 , 6.38239593],

        [2.94798323, 6.52559479, 6.4521226 , 0.        , 5.09021286],

        [2.98782637, 1.53530446, 6.38239593, 5.09021286, 0.        ]])


# The radii for which you want to measure. They need to be raised 

# up 2 extra dimensions to prepare for array broadcasting later

>>> radii = np.array([3,6,9])[:, None, None]


array([[[3]],

       [[6]],

       [[9]]])


# Count how many points fall within a certain radius from another

# point using numpy's array broadcasting. `d < radii` will return

# an array of `True/False` and we can count the number of `True`

# by `sum` over the last axis.

#

# The distance between a point to itself is 0 and we don't want

# to count that hence the -1.

>>> count = (d < radii).sum(axis=-1) - 1


array([[2, 1, 0, 1, 2],

       [3, 2, 0, 2, 3],

       [4, 4, 4, 4, 4]])


# Putting everything together for export

>>> result = pd.DataFrame(count, index=radii.flatten()).stack().to_frame('Count')

>>> result.index.names = ['Radius', 'PointID']


                Count

Radius PointID       

3      0            2

       1            1

       2            0

       3            1

       4            2

6      0            3

       1            2

       2            0

       3            2

       4            3

9      0            4

       1            4

       2            4

       3            4

       4            4

最終結(jié)果意味著在半徑 3 內(nèi),點 #0 有 2 個鄰居,點 #1 有 1 個鄰居,點 #2 有 0 個鄰居,依此類推。根據(jù)您的喜好重塑和格式化框架。


將其擴展到數(shù)千個點應該沒有問題。


查看完整回答
反對 回復 2022-05-24
  • 1 回答
  • 0 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號