apply() का उपयोग
apply आपके data के हर value, row, या column पर एक function चलाता है।
In this page:
Syntax
df["column"].apply(function_name)
df.apply(function_name, axis=0)
apply()
Series.apply(func) हर value पर func call करता है। DataFrame.apply(func, axis=0) हर column पर func चलाता है, और axis=1 हर row पर चलाता है। यह flexible है लेकिन vectorized operations से slower है, इसलिए जब कोई built-in method exist न करे तब इसे इस्तेमाल करें।
Note:
जब possible हो apply से df["a"] * 2 जैसे vectorized operations prefer करें।
उदाहरण: apply()
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df["a"].apply(lambda x: x ** 2))
print(df.apply(sum))
print(df.apply(lambda row: row["a"] + row["b"], axis=1))
# Output:
# 0 1
# 1 4
# 2 9
# Name: a, dtype: int64
# a 6
# b 60
# dtype: int64
# 0 11
# 1 22
# 2 33
# dtype: int64
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- जहाँ एक vectorized operation exist करती हो वहाँ apply इस्तेमाल करना
- row-wise काम के लिए axis=1 भूल जाना
- function से inconsistent types return करना
चैप्टर सारांश
- apply values पर एक function चलाता है
- axis=0 प्रति column है, axis=1 प्रति row
- यह vectorized code से slower है
- जब कोई built-in fit न हो तब इसे इस्तेमाल करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: