簡體   English   中英

Calling a Python function/class that takes an entire pandas dataframe or series as input, for all rows in another dataframe

[英]Calling a Python function/class that takes an entire pandas dataframe or series as input, for all rows in another dataframe

我有一個 Python class 需要一個 geopandas 系列或 Dataframe 來初始化(特別是與 geopandas 一起使用,但我想它是相同的解決方案)。 此 class 具有利用系列/數據幀中的各個列的屬性/方法。 除此之外,我有一個 dataframe 有很多行。 我想遍歷這個 dataframe(理想情況下以高效/並行的方式,因為每一行彼此獨立),並為每一行(又名系列)調用 class 中的一個方法。 並將 append 的結果作為 dataframe 的列。 但我在這方面遇到了麻煩。 使用標准列表理解/pandas apply() 方法,我可以這樣調用,例如:

gdf1['function_return_col'] = list(map((lambda f: my_function(f)), gdf2['date']))

但是如果說 function (或者在我的情況下,類)需要整個 gdf,我這樣稱呼:

gdf1['function_return_col'] = list(map((lambda f: my_function(f)), gdf2))

它不起作用,因為 'my_function()' 采用 dataframe 或系列,而發送給它的是 gdf2 的列名(字符串)。

How can I apply a function to all rows in a dataframe if said function takes an entire dataframe/series and not just select column(s)? 在我的具體情況下,因為它是 class 中的一個方法,所以我想這樣做,或者類似於在 dataframe 中的所有行上調用此方法:

gdf1['function_return_col'] = list(map((lambda f: my_class(f).my_method()), gdf2))

還是我只是以完全錯誤的方式思考這個問題?

您是否嘗試過使用稱為“應用”的 pandas dataframe 方法。
這是將它用於行軸和列軸的示例。

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2], 'B': [10, 20]})

df1 = df.apply(np.sum, axis=0)
print(df1)

df1 = df.apply(np.sum, axis=1)
print(df1)

暫無
暫無

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

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