简体   繁体   中英

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

I have a Python class that takes a geopandas Series or Dataframe to initialize (specifically working with geopandas, but I imagine it to be the same solution as pandas). This class has attributes/methods that utilize the various columns in the series/dataframe. Outside of this, I have a dataframe with many rows. I would like to iterate through (ideally in an efficient/parallel manner as each row is independent of each other) this dataframe, and call a method in the class for each row (aka Series). And append the results as a column to the dataframe. But I am having trouble with this. With the standard list comprehension/pandas apply() methods, I can call like this eg:

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

But if said function (or in my case, class) needs the entire gdf, and I call like this:

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

It does not work because 'my_function()' takes a dataframe or series, while what is being sent to it is the column names (strings) of 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)? In my specific case, since it's a method in a class, I would like to do this, or something similar to call this method on all rows in a dataframe:

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

Or am I just thinking of this in the entirely wrong way?

Have you tried using pandas dataframe method called "apply".
Here is an example of using it for both row axis and column axis.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM