There are scenarios where you might need to convert a Pandas DataFrame to Series. In this article, we’ll delve into the intricacies of this process, exploring different scenarios and providing detailed code examples along with their outputs.

## Prerequisites

Before we dive into the code examples, ensure you have the Pandas library installed. You can install it using the following pip command:

pip install pandas

## 9 Examples of converting Pandas Dataframe to Series

### Example 1: Converting a Single Column DataFrame to Series

Consider a scenario where you have a DataFrame with a single column. To convert this DataFrame to a Series, you can simply select the column using the square bracket notation.

import pandas as pd # Creating a DataFrame data = {'A': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) # Converting DataFrame to Series series = df['A'] print(series)

#### Output

0 1 1 2 2 3 3 4 4 5 Name: A, dtype: int64

In this example, we created a DataFrame with a single column ‘A’ and converted it to a Series. The resulting Series retains the original indices and data type.

### Example 2: Specifying Custom Index Labels

You can also assign custom index labels to the resulting Series.

# Creating a DataFrame data = {'A': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) # Converting DataFrame to Series with custom index custom_index = pd.Series(df['A'].values, index=['a', 'b', 'c', 'd', 'e']) print(custom_index)

**Output**

a 1 b 2 c 3 d 4 e 5 dtype: int64

In this example, we created a Series with custom index labels ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’.

### Example 3: Converting a DataFrame Slice to a Series

You can also extract a slice of a DataFrame and convert it to a Series.

# Creating a DataFrame data = {'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]} df = pd.DataFrame(data) # Converting a slice to a Series series = df['A'][1:4] print(series)

**Output**

1 2 2 3 3 4 Name: A, dtype: int64

In this example, we extracted rows 1 to 3 from column ‘A’ and converted it to a Series.

### Example 4: Converting a DataFrame Column with Mixed Data Types

If a DataFrame column contains mixed data types, the resulting Series will have an `object`

dtype.

# Creating a DataFrame with mixed data types data = {'A': [1, 'two', 3.0, 'four', 5]} df = pd.DataFrame(data) # Converting DataFrame to Series series = df['A'] print(series)

**Output**

0 1 1 two 2 3.0 3 four 4 5 Name: A, dtype: object

In this example, we have a DataFrame with mixed data types. When converted to a Series, the dtype is ‘object’.

### Example 5: Conversion with NaN Values

If the DataFrame contains NaN (Not a Number) values, they will be retained in the resulting Series.

import numpy as np # Creating a DataFrame with NaN values data = {'A': [1, np.nan, 3, 4, np.nan]} df = pd.DataFrame(data) # Converting DataFrame to Series series = df['A'] print(series)

**Output**

0 1.0 1 NaN 2 3.0 3 4.0 4 NaN Name: A, dtype: float64

In this example, we have NaN values in the DataFrame column ‘A’. When converted to a Series, the NaN values are retained.

### Example 6: Using iloc to Convert Specific Rows

You can use the `iloc`

indexer to select specific rows from a DataFrame and convert them to a Series.

# Creating a DataFrame data = {'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]} df = pd.DataFrame(data) # Converting specific rows to a Series series = df.iloc[1] print(series)

**Output**

A 2 B 7 Name: 1, dtype: int64

In this example, we used `iloc`

to select the second row of the DataFrame and converted it to a Series.

### Example 7: Converting a DataFrame to a Series with Numpy Functions

You can use NumPy functions in conjunction with DataFrame columns to perform calculations and then convert the result to a Series.

import numpy as np # Creating a DataFrame data = {'A': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) # Applying a NumPy function and converting to Series series = pd.Series(np.square(df['A'])) print(series)

**Output**

0 1 1 4 2 9 3 16 4 25 Name: A, dtype: int64

In this example, we applied the NumPy `square`

function to the column ‘A’ of the DataFrame and then converted it to a Series.

### Example 8: Multi-column DataFrame to Series with Custom Index Labels

In this example, we’ll convert a multi-column DataFrame to Series, assigning custom index labels.

# Creating a multi-column DataFrame data = {'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]} df = pd.DataFrame(data) # Converting DataFrame to Series with custom index labels custom_index = pd.Series(df['A'].values, index=['a', 'b', 'c', 'd', 'e']) print(custom_index)

**Output**

a 1 b 2 c 3 d 4 e 5 dtype: int64

In this Python code example, we first create a DataFrame `df`

with two columns ‘A’ and ‘B’. We then use the square bracket notation to select column ‘A’. Next, we use the `.values`

attribute to get the values of column ‘A’. Finally, we create a Series called `custom_index`

with custom index labels ‘a’, ‘b’, ‘c’, ‘d’, and ‘e’.

### Example 9: Applying a Custom Function in Series Conversion

Here, we’ll demonstrate how to apply a custom function during the conversion process.

# Creating a DataFrame data = {'A': [1, 2, 3, 4, 5]} df = pd.DataFrame(data) # Defining a custom function def custom_function(x): return x ** 2 # Applying the custom function and converting to Series series = df['A'].apply(custom_function) print(series)

**Output**

0 1 1 4 2 9 3 16 4 25 Name: A, dtype: int64

In this example, we create a DataFrame `df`

with a single column ‘A’. We define a custom function `custom_function`

that takes an input `x`

and returns its square. Next, we use the `.apply()`

function to apply this custom function to each element in column ‘A’. The result is a Series where each element is the square of the corresponding element in the original column.

## Conclusion

Converting a **Pandas DataFrame to Series** is a straightforward process with various options depending on your specific requirements. By using the examples provided in this article, you should now have a solid understanding of how to perform this conversion in different scenarios. Remember to leverage these techniques in your data manipulation tasks to enhance your data analysis skills.

On this site, we have more informative articles on Pandas Dataframe for you, so you can read them as well.

Thank you for giving your valuable time to this informative article.