05-01-2023, 01:30 AM
Pandas Series Object – A Helpful Guide with Examples
5/5 – (1 vote)
If you’re working with data in Python, you might have come across the pandas library.![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
One of the key components of pandas is the Series object, which is a one-dimensional, labeled array capable of holding data of any type, such as integers, strings, floats, and even Python objects
.
The Series object serves as a foundation for organizing and manipulating data within the pandas library.
This article will teach you more about this crucial data structure and how it can benefit your data analysis workflows. Let’s get started!![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Creating a Pandas Series
![[Image: image-139-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-139-1024x682.png)
In this section, you’ll learn how to create a Pandas Series, a powerful one-dimensional labeled array capable of holding any data type.
To create a Series, you can use the constructor from the Pandas library.
Make sure you have Pandas installed and imported:
Now, you can create a Series using the function, and pass in various data structures like lists, dictionaries, or even scalar values. For example:
The constructor accepts various parameters that help you customize the resulting series, including:
Here’s an example of creating a Series with a custom index:
When you create a Series object with a dictionary, Pandas automatically takes the keys as the index and the values as the series data:
Remember: Your Series can hold various data types, including strings, numbers, and even objects.
Pandas Series Indexing
![[Image: image-142.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-142.png)
Next, you’ll learn the best ways to index and select data from a Pandas Series, making your data analysis tasks more manageable and enjoyable.
Again, a Pandas Series is a one-dimensional labeled array, and it can hold various data types like integers, floats, and strings. The series object contains an index, which serves multiple purposes, such as metadata identification, automatic and explicit data alignment, and intuitive data retrieval and modification
.
There are two types of indexing available in a Pandas Series:
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJQBOpbhxQrM%2Fhqdefault.jpg)
Recommended: Pandas and – A Simple Guide with Video
Let’s examine some examples of indexing and selection in a Pandas Series:
Keep in mind that while working with Pandas Series, the index labels do not have to be unique but must be hashable types. This means they should be of immutable data types like strings, numbers, or tuples
.
Recommended: Mutable vs. Immutable Objects in Python
Accessing Values in a Pandas Series
![[Image: image-146-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-146-1024x682.png)
So you’re working with Pandas Series and want to access their values. I already showed you this in the previous section but let’s repeat this once again. Repetition. Repetition. Repetition!
First of all, create your Pandas Series:
Now that you have your Series, let’s talk about accessing its values
:
Iterating through a Pandas Series
![[Image: image-143.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-143.png)
Although iterating over a Series is possible, it’s generally discouraged in the Pandas community due to its suboptimal performance. Instead, try using vectorization or other optimized methods, such as , , or .
This section will discuss Series iteration methods, but always remember to consider potential alternatives first!
When you absolutely need to iterate through a Series, you can use the function, which returns an iterator of index-value pairs. Here’s an example:
Another method to iterate over a Pandas Series is by converting it into a list using the function, like this:
However, keep in mind that these approaches are suboptimal and should be avoided whenever possible. Instead, try one of the following efficient techniques:
Sorting a Pandas Series![[Image: 1f504.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f504.png)
![[Image: image-141-1024x804.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-141-1024x804.png)
Sorting a Pandas Series is pretty straightforward. With the function, you can easily reorder your series, either in ascending or descending order.
First, you must import the Pandas library and create a Pandas Series:
To sort the values in the series, just use the function like this:
By default, the values will be sorted in ascending order. If you want to sort them in descending order, just set the parameter to :
You can also control the sorting method using the parameter. Supported options are , , and . For example:
When dealing with missing values () in your series, you can use the parameter to specify their position in the sorted series. The default value is , which places missing values at the end.
To put them at the beginning of the sorted series, just set the parameter to :
Applying Functions to a Pandas Series
You might come across situations where you want to apply a custom function to your Pandas Series. Let’s dive into how you can do that using the method. ![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgkA5wd7RYAU%2Fhqdefault.jpg)
To begin with, the method is quite flexible and allows you to apply a wide range of functions on your Series. These functions could be NumPy’s universal functions (), built-in Python functions, or user-defined functions. Regardless of the type, will work like magic.![[Image: 1f3a9.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f3a9.png)
![[Image: 2728.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png)
For instance, let’s say you have a Pandas Series containing square numbers, and you want to find the square root of these numbers:
Now, you can use the method along with the built-in Python function to calculate the square root:
You’ll get the following output:
Great job!
Now, let’s consider you want to create your own function to check if the numbers in a Series are even. Here’s how you can achieve that:
And the output would look like this:
Congratulations!
You’ve successfully used the method with a custom function.
Replacing Values in a Pandas Series
![[Image: image-145-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-145-1024x682.png)
You might want to replace specific values within a Pandas Series to clean up your data or transform it into a more meaningful format. The function is here to help you do that! ![[Image: 1f603.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png)
How to use
To use the function, simply call it on your Series object like this: . is the value you want to replace, and is the new value you want to insert instead. You can also use regex for more advanced replacements.
Let’s see an example:
This code will replace the value with the string in your Series. ![[Image: 1f504.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f504.png)
Multiple replacements
You can replace multiple values simultaneously by passing a dictionary or two lists to the function. For example:
In this case, will be replaced with and with . ![[Image: 1f389.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png)
Limiting replacements
You can limit the number of replacements by providing the parameter. For example, if you set , only the first occurrence of the value will be replaced.
This code will replace only the first occurrence of with in the Series. ![[Image: 2728.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png)
Appending and Concatenating Pandas Series
You might want to combine your pandas Series while working with your data. Worry not!
Pandas provides easy and convenient ways to append and concatenate your Series.
Appending Series
Appending Series can be done using the method. It allows you to concatenate two or more Series objects. To use it, simply call the method on one series and pass the other series as the argument.
For example:
Output:
However, appending Series iteratively may become computationally expensive. In such cases, consider using instead. ![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Concatenating Series
The function is more efficient when you need to combine multiple Series vertically. Simply provide a list of Series you want to concatenate as its argument, like so:
Output:
There you have it! You’ve combined your Pandas Series using and .
Renaming a Pandas Series
![[Image: image-340.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-340.png)
Renaming a Pandas Series is a simple yet useful operation you may need in your data analysis process.
To start, the method in Pandas can be used to alter the index labels or name of a given Series object. But, if you just want to change the name of the Series, you can set the attribute directly. For instance, if you have a Series object called , you can rename it to like this:
Now, let’s say you want to rename the index labels of your Series. You can do this using the method. Here’s an example:
The method also accepts functions for more complex transformations. For example, if you want to capitalize all index labels, you can do it like this:
Keep in mind that the method creates a new Series by default and doesn’t modify the original one. If you want to change the original Series in-place, just set the argument to :
Unique Values in a Pandas Series
![[Image: image-341.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-341.png)
To find unique values in a Pandas Series, you can use the method
. This method returns the unique values in the series without sorting them, maintaining the order of appearance.
Here’s a quick example:
The output will be:
When working with missing values, keep in mind that the method includes NaN values if they exist in the series. This behavior ensures you are aware of missing data in your dataset
.
If you need to find unique values in multiple columns, the method might not be the best choice, as it only works with Series objects, not DataFrames. Instead, use the method to get unique combinations of multiple columns.
Recommended: The Ultimate Guide to Data Cleaning in Python and Pandas
To summarize, when finding unique values in a Pandas Series:
With these tips, you’re ready to efficiently handle unique values in your Pandas data analysis!![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
![[Image: 1f4bb.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4bb.png)
Converting Pandas Series to Different Data Types
![[Image: image-342.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-342.png)
You can convert a Pandas Series to different data types to modify your data and simplify your work. In this section, you’ll learn how to transform a Series into a DataFrame, List, Dictionary, Array, String, and Numpy Array. Let’s dive in!![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
Series to DataFrame
To convert a Series to a DataFrame, use the method. Here’s how:
This code will output:
Series to List
For transforming a Series to a List, simply call the method, like this:
Output:
Series to Dictionary
To convert your Series into a Dictionary, use the method:
This results in:
The keys are now indexes, and the values are the original Series data.
Series to Array
Convert your Series to an Array by accessing its attribute:
Output:
Series to String
To join all elements of a Series into a single String, use the function from the library:
This will result in:
Series to Numpy Array
For converting a Series into a Numpy Array, call the method:
Output:
Now you’re all set to manipulate your Pandas Series objects and adapt them to different data types!![[Image: 1f389.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png)
Python Pandas Series in Practice![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
![[Image: 1f4bb.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4bb.png)
![[Image: image-343.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-343.png)
A Pandas Series is a one-dimensional array-like object that’s capable of holding any data type. It’s one of the essential data structures in the Pandas library, along with the DataFrame. Series is an easy way to organize and manipulate your data, especially when dealing with labeled data, such as SQL databases or dictionary keys.![[Image: 1f511.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f511.png)
![[Image: 26a1.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/26a1.png)
To begin, import the Pandas library, which is usually done with the alias ‘‘:
Creating a Pandas Series ![[Image: 1f4dd.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4dd.png)
![[Image: 1f528.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f528.png)
To create a Series, simply pass a list, ndarray, or dictionary to the function. For example, you can create a Series with integers:
Or with strings:
In case you want your Series to have an explicit index, you can specify the parameter:
Accessing and Manipulating Series Data ![[Image: 1f6aa.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f6aa.png)
![[Image: 1f527.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f527.png)
Now that you have your Series, here’s how you can access and manipulate the data:
These are just a few examples of interacting with a Pandas Series. There are many other functionalities you can explore!
Practice makes perfect, so feel free to join our free email academy where I’ll show you practical coding projects, data science, exponential technologies in AI and blockchain engineering, Python, and much more. How can you join? Simply download your free cheat sheets by entering your name here:
Let your creativity run wild and happy coding!![[Image: 1f917.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f917.png)
5/5 – (1 vote)
If you’re working with data in Python, you might have come across the pandas library.
![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
One of the key components of pandas is the Series object, which is a one-dimensional, labeled array capable of holding data of any type, such as integers, strings, floats, and even Python objects
.The Series object serves as a foundation for organizing and manipulating data within the pandas library.
This article will teach you more about this crucial data structure and how it can benefit your data analysis workflows. Let’s get started!
![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Creating a Pandas Series
![[Image: image-139-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-139-1024x682.png)
In this section, you’ll learn how to create a Pandas Series, a powerful one-dimensional labeled array capable of holding any data type.
To create a Series, you can use the
Code:
Series()Make sure you have Pandas installed and imported:
Code:
import pandas as pdNow, you can create a Series using the
Code:
pd.Series()Code:
my_list = [1, 2, 3, 4]
my_series = pd.Series(my_list)The
Code:
Series()- : This is the input data—arrays, dicts, or scalars.Code:
data
- : You can provide a custom index for your series to label the values. If you don’t supply one, Pandas will automatically create an integer index (0, 1, 2…).Code:
index
Here’s an example of creating a Series with a custom index:
Code:
custom_index = ['a', 'b', 'c', 'd']
my_series = pd.Series(my_list, index=custom_index)When you create a Series object with a dictionary, Pandas automatically takes the keys as the index and the values as the series data:
Code:
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
my_series = pd.Series(my_dict)
Remember: Your Series can hold various data types, including strings, numbers, and even objects.Pandas Series Indexing
![[Image: image-142.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-142.png)
Next, you’ll learn the best ways to index and select data from a Pandas Series, making your data analysis tasks more manageable and enjoyable.
Again, a Pandas Series is a one-dimensional labeled array, and it can hold various data types like integers, floats, and strings. The series object contains an index, which serves multiple purposes, such as metadata identification, automatic and explicit data alignment, and intuitive data retrieval and modification
.There are two types of indexing available in a Pandas Series:
- Position-based indexing – this uses integer positions to access data. The pandas function comes in handy for this purpose.Code:
iloc[]
- Label-based indexing – this uses index labels for data access. The pandas function works great for this type of indexing.Code:
loc[]
Recommended: Pandas Code:
loc()Code:
iloc()Let’s examine some examples of indexing and selection in a Pandas Series:
Code:
import pandas as pd # Sample Pandas Series
data = pd.Series([10, 20, 30, 40, 50], index=['a', 'b', 'c', 'd', 'e']) # Position-based indexing (using iloc)
position_index = data.iloc[2] # Retrieves the value at position 2 (output: 30) # Label-based indexing (using loc)
label_index = data.loc['b'] # Retrieves the value with the label 'b' (output: 20)Keep in mind that while working with Pandas Series, the index labels do not have to be unique but must be hashable types. This means they should be of immutable data types like strings, numbers, or tuples
.
Recommended: Mutable vs. Immutable Objects in PythonAccessing Values in a Pandas Series
![[Image: image-146-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-146-1024x682.png)
So you’re working with Pandas Series and want to access their values. I already showed you this in the previous section but let’s repeat this once again. Repetition. Repetition. Repetition!
First of all, create your Pandas Series:
Code:
import pandas as pd data = ['A', 'B', 'C', 'D', 'E']
my_series = pd.Series(data)Now that you have your Series, let’s talk about accessing its values
:- Using index: You can access an element in a Series using its index, just like you do with lists:
Code:
third_value = my_series[2]
print(third_value) # Output: C- Using : Access an element using its index label with theCode:
.loc[]accessor, which is useful when you have custom index namesCode:.loc[]
:
Code:
data = ['A', 'B', 'C', 'D', 'E']
index_labels = ['one', 'two', 'three', 'four', 'five']
my_series = pd.Series(data, index=index_labels) second_value = my_series.loc['two']
print(second_value) # Output: B- Using : Access a value based on its integer position with theCode:
.iloc[]accessor. This is particularly helpful when you have non-integer index labelsCode:.iloc[]
:
Code:
value_at_position_3 = my_series.iloc[2]
print(value_at_position_3) # Output: CIterating through a Pandas Series
![[Image: image-143.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-143.png)
Although iterating over a Series is possible, it’s generally discouraged in the Pandas community due to its suboptimal performance. Instead, try using vectorization or other optimized methods, such as Code:
applyCode:
transformCode:
aggThis section will discuss Series iteration methods, but always remember to consider potential alternatives first!
When you absolutely need to iterate through a Series, you can use the
Code:
iteritems()Code:
for idx, val in your_series.iteritems(): # Do something with idx and valAnother method to iterate over a Pandas Series is by converting it into a list using the
Code:
tolist()Code:
for val in your_series.tolist(): # Do something with val
However, keep in mind that these approaches are suboptimal and should be avoided whenever possible. Instead, try one of the following efficient techniques:- Vectorized operations: Apply arithmetic or comparison operations directly on the Series.
- Use : Apply a custom function element-wise.Code:
apply()
- Use : Aggregate multiple operations to be applied.Code:
agg()
- Use : Apply a function and return a similarly-sized Series.Code:
transform()
Sorting a Pandas Series
![[Image: 1f504.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f504.png)
![[Image: image-141-1024x804.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-141-1024x804.png)
Sorting a Pandas Series is pretty straightforward. With the
Code:
sort_values()First, you must import the Pandas library and create a Pandas Series:
Code:
import pandas as pd
s = pd.Series([100, 200, 54.67, 300.12, 400])To sort the values in the series, just use the
Code:
sort_values()Code:
sorted_series = s.sort_values()By default, the values will be sorted in ascending order. If you want to sort them in descending order, just set the
Code:
ascendingCode:
FalseCode:
sorted_series = s.sort_values(ascending=False)You can also control the sorting method using the
Code:
kindCode:
'quicksort'Code:
'mergesort'Code:
'heapsort'Code:
sorted_series = s.sort_values(kind='mergesort')When dealing with missing values (
Code:
NaNCode:
na_positionCode:
'last'To put them at the beginning of the sorted series, just set the
Code:
na_positionCode:
'first'Code:
sorted_series = s.sort_values(na_position='first')You might come across situations where you want to apply a custom function to your Pandas Series. Let’s dive into how you can do that using the
Code:
apply()![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
To begin with, the
Code:
apply()Code:
ufuncsCode:
apply()![[Image: 1f3a9.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f3a9.png)
![[Image: 2728.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png)
For instance, let’s say you have a Pandas Series containing square numbers, and you want to find the square root of these numbers:
Code:
import pandas as pd square_numbers = pd.Series([4, 9, 16, 25, 36])Now, you can use the
Code:
apply()Code:
sqrt()Code:
import math square_roots = square_numbers.apply(math.sqrt)
print(square_roots)You’ll get the following output:
Code:
0 2.0
1 3.0
2 4.0
3 5.0
4 6.0
dtype: float64Great job!
Now, let’s consider you want to create your own function to check if the numbers in a Series are even. Here’s how you can achieve that:Code:
def is_even(number): return number % 2 == 0 even_numbers = square_numbers.apply(is_even)
print(even_numbers)And the output would look like this:
Code:
0 True
1 False
2 True
3 False
4 True
dtype: boolCongratulations!
You’ve successfully used the Code:
apply()Replacing Values in a Pandas Series
![[Image: image-145-1024x682.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-145-1024x682.png)
You might want to replace specific values within a Pandas Series to clean up your data or transform it into a more meaningful format. The
Code:
replace()![[Image: 1f603.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f603.png)
How to use
Code:
replace()To use the
Code:
replace()Code:
your_series.replace(to_replace, value)Code:
to_replaceCode:
valueLet’s see an example:
Code:
import pandas as pd data = pd.Series([1, 2, 3, 4])
data = data.replace(2, "Two")
print(data)This code will replace the value
Code:
2Code:
"Two"![[Image: 1f504.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f504.png)
Multiple replacements
You can replace multiple values simultaneously by passing a dictionary or two lists to the function. For example:
Code:
data = pd.Series([1, 2, 3, 4])
data = data.replace({1: 'One', 4: 'Four'})
print(data)In this case,
Code:
1Code:
'One'Code:
4Code:
'Four'![[Image: 1f389.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png)
Limiting replacements
You can limit the number of replacements by providing the
Code:
limitCode:
limit=1Code:
data = pd.Series([2, 2, 2, 2])
data = data.replace(2, "Two", limit=1)
print(data)This code will replace only the first occurrence of
Code:
2Code:
"Two"![[Image: 2728.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png)
Appending and Concatenating Pandas Series
You might want to combine your pandas Series while working with your data. Worry not!
Pandas provides easy and convenient ways to append and concatenate your Series.Appending Series
Appending Series can be done using the
Code:
append()For example:
Code:
import pandas as pd series1 = pd.Series([1, 2, 3])
series2 = pd.Series([4, 5, 6]) result = series1.append(series2)
print(result)Output:
Code:
0 1
1 2
2 3
0 4
1 5
2 6
dtype: int64However, appending Series iteratively may become computationally expensive. In such cases, consider using
Code:
concat()![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
Concatenating Series
The
Code:
concat()Code:
import pandas as pd series_list = [ pd.Series(range(1, 6), index=list('abcde')), pd.Series(range(1, 6), index=list('fghij')), pd.Series(range(1, 6), index=list('klmno'))
] combined_series = pd.concat(series_list)
print(combined_series)Output:
Code:
a 1
b 2
c 3
d 4
e 5
f 1
g 2
h 3
i 4
j 5
k 1
l 2
m 3
n 4
o 5
dtype: int64
There you have it! You’ve combined your Pandas Series using Code:
append()Code:
concat()Renaming a Pandas Series
![[Image: image-340.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-340.png)
Renaming a Pandas Series is a simple yet useful operation you may need in your data analysis process.
To start, the
Code:
rename()Code:
nameCode:
my_seriesCode:
"New_Name"Code:
my_series.name = "New_Name"Now, let’s say you want to rename the index labels of your Series. You can do this using the
Code:
rename()Code:
renamed_series = my_series.rename(index={"old_label1": "new_label1", "old_label2": "new_label2"})The
Code:
rename()Code:
capitalized_series = my_series.rename(index=lambda x: x.capitalize())Keep in mind that the
Code:
rename()Code:
inplaceCode:
TrueCode:
my_series.rename(index={"old_label1": "new_label1", "old_label2": "new_label2"}, inplace=True)![[Image: image-341.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-341.png)
To find unique values in a Pandas Series, you can use the
Code:
unique()
. This method returns the unique values in the series without sorting them, maintaining the order of appearance.Here’s a quick example:
Code:
import pandas as pd data = {'A': [1, 2, 1, 4, 5, 4]}
series = pd.Series(data['A']) unique_values = series.unique()
print(unique_values)The output will be:
Code:
[1, 2, 4, 5]When working with missing values, keep in mind that the
Code:
unique()
.If you need to find unique values in multiple columns, the
Code:
unique()Code:
.drop_duplicates()
Recommended: The Ultimate Guide to Data Cleaning in Python and PandasTo summarize, when finding unique values in a Pandas Series:
- Use the method for a single columnCode:
unique()![[Image: 1f9ea.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f9ea.png)
- Remember that values will be included as unique values when presentCode:
NaN![[Image: 1f4cc.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4cc.png)
- Use the method for multiple columns when neededCode:
.drop_duplicates()![[Image: 1f504.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f504.png)
With these tips, you’re ready to efficiently handle unique values in your Pandas data analysis!
![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
![[Image: 1f4bb.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4bb.png)
Converting Pandas Series to Different Data Types
![[Image: image-342.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-342.png)
You can convert a Pandas Series to different data types to modify your data and simplify your work. In this section, you’ll learn how to transform a Series into a DataFrame, List, Dictionary, Array, String, and Numpy Array. Let’s dive in!
![[Image: 1f680.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png)
Series to DataFrame
To convert a Series to a DataFrame, use the
Code:
to_frame()Code:
import pandas as pd data = pd.Series([1, 2, 3, 4])
df = data.to_frame()
print(df)This code will output:
Code:
0
0 1
1 2
2 3
3 4For transforming a Series to a List, simply call the
Code:
tolist()Code:
data_list = data.tolist()
print(data_list)Output:
Code:
[1, 2, 3, 4]To convert your Series into a Dictionary, use the
Code:
to_dict()Code:
data_dict = data.to_dict()
print(data_dict)This results in:
Code:
{0: 1, 1: 2, 2: 3, 3: 4}The keys are now indexes, and the values are the original Series data.
Series to Array
Convert your Series to an Array by accessing its
Code:
.arrayCode:
data_array = data.array
print(data_array)Output:
Code:
<PandasArray>
[1, 2, 3, 4]To join all elements of a Series into a single String, use the
Code:
join()Code:
strCode:
data_str = ''.join(map(str, data))
print(data_str)This will result in:
Code:
1234For converting a Series into a Numpy Array, call the
Code:
to_numpy()Code:
import numpy as np data_numpy = data.to_numpy()
print(data_numpy)Output:
Code:
array([1, 2, 3, 4], dtype=int64)Now you’re all set to manipulate your Pandas Series objects and adapt them to different data types!
![[Image: 1f389.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f389.png)
Python Pandas Series in Practice
![[Image: 1f43c.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f43c.png)
![[Image: 1f4bb.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4bb.png)
![[Image: image-343.png]](https://blog.finxter.com/wp-content/uploads/2023/04/image-343.png)
A Pandas Series is a one-dimensional array-like object that’s capable of holding any data type. It’s one of the essential data structures in the Pandas library, along with the DataFrame. Series is an easy way to organize and manipulate your data, especially when dealing with labeled data, such as SQL databases or dictionary keys.
![[Image: 1f511.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f511.png)
![[Image: 26a1.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/26a1.png)
To begin, import the Pandas library, which is usually done with the alias ‘
Code:
pdCode:
import pandas as pd![[Image: 1f4dd.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f4dd.png)
![[Image: 1f528.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f528.png)
To create a Series, simply pass a list, ndarray, or dictionary to the
Code:
pd.Series()Code:
integer_series = pd.Series([1, 2, 3, 4, 5])Or with strings:
Code:
string_series = pd.Series(['apple', 'banana', 'cherry'])In case you want your Series to have an explicit index, you can specify the
Code:
indexCode:
indexed_series = pd.Series(['apple', 'banana', 'cherry'], index=['a', 'b', 'c'])![[Image: 1f6aa.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f6aa.png)
![[Image: 1f527.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f527.png)
Now that you have your Series, here’s how you can access and manipulate the data:
- Accessing data by index (using both implicit and explicit index):
- First item: orCode:
integer_series[0]Code:indexed_series['a']
- Slicing: Code:
integer_series[1:3]
- First item:
- Adding new data:
- Append: Code:
string_series.append(pd.Series(['date']))
- Add with a label: Code:
indexed_series['d'] = 'date'
- Append:
- Common Series methods:
- – Check if all elements are trueCode:
all()
- – Check if any elements are trueCode:
any()
- – Get unique valuesCode:
unique()
- – Compare elements element-wise with another SeriesCode:
ge(another_series)
These are just a few examples of interacting with a Pandas Series. There are many other functionalities you can explore!
Practice makes perfect, so feel free to join our free email academy where I’ll show you practical coding projects, data science, exponential technologies in AI and blockchain engineering, Python, and much more. How can you join? Simply download your free cheat sheets by entering your name here:
Let your creativity run wild and happy coding!
![[Image: 1f917.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f917.png)

