ホームページ  >  記事  >  バックエンド開発  >  Python で Pandas シリーズの関数を適用するために引数を渡す方法は?

Python で Pandas シリーズの関数を適用するために引数を渡す方法は?

Linda Hamilton
Linda Hamiltonオリジナル
2024-10-22 22:50:02160ブラウズ

How to Pass Arguments to Apply Functions for Pandas Series in Python?

Python Pandas のシリーズ適用関数に引数を渡す

パンダ ライブラリは、'apply()' メソッドを提供しますシリーズの各要素に関数を適用します。ただし、古いバージョンの pandas では、追加の引数を関数に渡すことはできません。

古いバージョンの Pandas の解決策:

古いバージョンでこの制限に対処するにはパンダの場合、'functools.partial()' または 'lambda' 関数を使用できます:

Using 'functools.partial()':

<code class="python">import functools
import operator

# Define a function with multiple arguments
def add_3(a, b, c):
    return a + b + c

# Create a partial function by binding extra arguments
add_3_partial = functools.partial(add_3, 2, 3)

# Apply the partial function to a series
series.apply(add_3_partial)</code>

「lambda」の使用:

<code class="python"># Create a lambda function to pass extra arguments to the apply method
lambda_func = lambda x: my_function(a, b, c, d, ..., x)

# Apply the lambda function to the series
series.apply(lambda_func)</code>

新しいバージョンの Pandas の解決策:

2017 年 10 月以降、pandas は位置引数とキーワード引数の両方を 'apply()' メソッドに直接渡すことをサポートしています。

<code class="python">series.apply(my_function, args=(2, 3, 4), extra_kw={"example": 5})</code>

この構文では、位置引数は の要素の後に追加されます。シリーズ。キーワード引数は辞書として渡されます。

以上がPython で Pandas シリーズの関数を適用するために引数を渡す方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。