In Pandas, what method is used to apply a function to each element of a Series?

pivot()
melt()
sort_values()
apply()

The correct answer is D. apply().

The apply() method is used to apply a function to each element of a Series. The function can be any Python function, and it can take any number of arguments. The apply() method returns a new Series with the results of the function applied to each element of the original Series.

The pivot() method is used to pivot a DataFrame. This means that it changes the DataFrame’s columns into rows and the rows into columns. The melt() method is used to melt a DataFrame. This means that it changes the DataFrame’s columns into a single column with multiple values. The sort_values() method is used to sort a DataFrame by one or more columns.

Here is an example of how to use the apply() method:

“`
import pandas as pd

df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6]})

result = df.apply(lambda x: x * 2)

print(result)

Table of Contents

A B

2 8

4 12

6 18

“`

In this example, the apply() method is used to multiply each element of the df DataFrame by 2. The result is a new DataFrame with the values of the original DataFrame multiplied by 2.