![]() |
|
[Tut] Pandas Series Object – A Helpful Guide with Examples - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Pandas Series Object – A Helpful Guide with Examples (/thread-101080.html) |
[Tut] Pandas Series Object – A Helpful Guide with Examples - xSicKxBot - 05-01-2023 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. ![]() 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! ![]() Creating a Pandas Series ![]() 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()
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 ![]() 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:
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 ![]() 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 :
Code: third_value = my_series[2]
print(third_value) # Output: C
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
Code: value_at_position_3 = my_series.iloc[2]
print(value_at_position_3) # Output: CIterating through a Pandas Series ![]() 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:
Sorting a Pandas Series ![]() ![]() 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()![]() To begin with, the Code: apply()Code: ufuncsCode: apply()![]() ![]() 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 ![]() 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()![]() 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"![]() 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'![]() 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"![]() 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()![]() 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 ![]() 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)![]() 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:
With these tips, you’re ready to efficiently handle unique values in your Pandas data analysis! ![]() ![]() Converting Pandas Series to Different Data Types ![]() 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! ![]() 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! ![]() Python Pandas Series in Practice ![]() ![]() ![]() 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. ![]() ![]() To begin, import the Pandas library, which is usually done with the alias ‘ Code: pdCode: import pandas as pd![]() ![]() 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'])![]() ![]() 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! ![]()
|