Pandas.apply allow the users to pass a function and apply it on every single value of the Pandas series. It comes as a huge improvement for the pandas library as this function helps to segregate data according to the conditions required due to which it is efficiently used in data science and machine learning.
Import the Pandas module into the python file using the following commands on the terminal:
pip install pandas
To read the csv file and squeezing it into a pandas series following commands are used:
import pandas as pd s = pd.read_csv("stock.csv", squeeze=True)
s.apply(func, convert_dtype=True, args=())
func: .apply takes a function and applies it to all values of pandas series.
convert_dtype: Convert dtype as per the function’s operation.
args=(): Additional arguments to pass to function instead of series.
Return Type: Pandas Series after applied function/operation.
For the dataset, click here to download.
The following example passes a function and checks the value of each element in series and returns low, normal or High accordingly.
In the following example, a temporary anonymous function is made in .apply itself using lambda. It adds 5 to each value in series and returns a new series.
0 50.12 1 54.10 2 54.65 3 52.38 4 52.95 Name: Stock Price, dtype: float64 0 55.12 1 59.10 2 59.65 3 57.38 4 57.95 Name: Stock Price, dtype: float64 3007 772.88 3008 771.07 3009 773.18 3010 771.61 3011 782.22 Name: Stock Price, dtype: float64 3007 777.88 3008 776.07 3009 778.18 3010 776.61 3011 787.22 Name: Stock Price, dtype: float64
As observed, New values = old values + 5
- Important differences between Python 2.x and Python 3.x with examples
- Python | Convert list to Python array
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Visualizing O(n) using Python
- Python vs PHP
- zip() in Python
- try and except in Python
- Python Set | pop()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.