The Wayback Machine - https://web.archive.org/web/20241126230430/https://www.geeksforgeeks.org/python-pandas-series-combine/
Open In App

Python | Pandas Series.combine()

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages.

Pandas

is one of those packages and makes importing and analyzing data much easier. Pandas

Series.combine()

is a series mathematical operation method. This is used to combine two series into one. The shape of output series is same as the caller series. The elements are decided by a function passed as parameter to

combine()

method. The shape of both series has to be same otherwise it will throw an error.

Syntax: Series.combine(other, func, fill_value=nan) Parameters: other: other series or list type to be combined with caller series func: Function passed as parameter which will decide from which series the element should be put at that index fill_value: integer value of level in case of multi index Return: Combined series with same shape as caller series

Example #1:

In this example, two lists are made and converted into pandas series using .Series() method. A function is made using lambda which checks which values is smaller in both series and returns whichever is the smaller.

Python3
# importing pandas module
import pandas as pd

# creating first series
first =[1, 2, 5, 6, 3, 7, 11, 0, 4]

# creating second series
second =[5, 3, 2, 1, 3, 9, 21, 3, 1]

# making series
first = pd.Series(first)

# making seriesa
second = pd.Series(second)

# calling .combine() method
result = first.combine(second, (lambda x1, x2: x1 if x1 < x2 else x2))

# display
result

Output:

As shown in the output image, the returned series is having smaller values from both series.

Example #2:

In this example, Null values are passed too using

Numpy.nan

method. Since series contains null values, 5 is passed to fill_value parameter to replace null values by 5. A lambda function is passed which will compare values in both series and will return the greater one.

Python3
# importing pandas module
import pandas as pd

# importing numpy module
import numpy as np

# creating first series
first =[1, 2, np.nan, 5, 6, 3, np.nan, 7, 11, 0, 4, 8]

# creating second series
second =[5, 3, 2, np.nan, 1, 3, 9, 21, 3, np.nan, 1, np.nan]

# making series
first = pd.Series(first)

# making seriesa
second = pd.Series(second)

# calling .combine() method
result = first.combine(second, func =(lambda x1, x2: x1 if x1 > x2 else x2), fill_value = 5)

# display
result

Output:

As shown in the output, the NaN values in the series were replaced by 5 before combining the series.


0      5.0
1 3.0
2 2.0
3 NaN
4 6.0
5 3.0
6 9.0
7 21.0
8 11.0
9 NaN
10 4.0
11 NaN
dtype: float64

Previous Article
Next Article

Similar Reads

Combine two Pandas series into a DataFrame
In this post, we will learn how to combine two series into a DataFrame? Before starting let's see what a series is?Pandas Series is a one-dimensional labeled array capable of holding any data type. In other terms, Pandas Series is nothing but a column in an excel sheet. There are several ways to concatenate two series in pandas. Following are some
3 min read
Add a Pandas series to another Pandas series
Let us see how to add a Pandas series to another series in Python. This can be done using 2 ways: append()concat() Method 1: Using the append() function: It appends one series object at the end of another series object and returns an appended series. The attribute, ignore_index=True is used when we do not use index values on appending, i.e., the re
2 min read
Pandas Series dt.weekofyear Method | Get Week of Year in Pandas Series
The dt.weekofyear attribute returns a Series containing the week ordinal of the year in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.dayofweek | Get Day of Week from DateTime Series in Pandas
Pandas dt.dayofweek attribute returns the day of the week from the given DateTime Series Object. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:
2 min read
Pandas Series dt.freq | Retrieve Frequency of Pandas Time Series
Pandas dt.freq attribute returns the time series frequency applied on the given series object if any, else it returns None. Examples C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_da
2 min read
Pandas Series dt.daysinmonth | Get Number of Days in Month in Pandas Series
The dt.daysinmonth attribute returns the number of days in the month for the given DateTime series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result
2 min read
Pandas Series dt.normalize() | Normalize Time in Pandas Series
The dt.normalize() method converts times to midnight. The time component of the date-time is converted to midnight i.e. 00:00:00. This is useful in cases when the time does not matter. Length is unaltered. The time zones are unaffected. Example: C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 09:45', periods = 5, freq = 'M',
2 min read
How to combine two dataframe in Python - Pandas?
Combining two DataFrames in Pandas involves concat() and merge() function to join data based on common columns or indices. Let's understand with a quick example: [GFGTABS] Python import pandas as pd # Create two sample DataFrames df1 = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]}) df2 = pd.DataFrame({
5 min read
How to combine Groupby and Multiple Aggregate Functions in Pandas?
Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library. Groupby() Pandas dataframe.groupby() function is used to split the data in dataframe int
1 min read
Combine Multiple Excel Worksheets Into a Single Pandas Dataframe
Prerequisites: Working with excel files using Pandas In these articles, we will discuss how to Import multiple excel sheet into a single DataFrame and save into a new excel file. Let's suppose we have two Excel files with the same structure (Excel_1.xlsx, Excel_2.xlsx), then merge both of the sheets into a new Excel file. Approach : Import-ModuleRe
1 min read
Python | Pandas series.cumprod() to find Cumulative product of a Series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cumprod() is used to find Cumulative product of a series. In cumulative product, the length of returned series is same as
3 min read
Python | Pandas Series.str.replace() to replace text in a series
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. Pandas Series.str.replace() method works like Python .replace() method only, but it works on Series too. Before calling .replace() on a Panda
5 min read
Python | Pandas Series.astype() to convert Data type of series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas astype() is the one of the most important methods. It is used to change data type of a series. When data frame is made from a csv
2 min read
Python | Pandas Series.cumsum() to find cumulative sum of a Series
Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements. Syntax: Series.cumsum(axis=None, skipna=True) Parameters: axis: 0 or 'index' for row wise operation and 1 or 'columns' for column wise operation skipna: Skip
2 min read
Python | Pandas series.cummax() to find Cumulative maximum of a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative maximum, the length of returned series is same as i
2 min read
Python | Pandas Series.cummin() to find cumulative minimum of a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummin() is used to find Cumulative minimum of a series. In cumulative minimum, the length of returned series is same as i
2 min read
Python | Pandas Series.nonzero() to get Index of all non zero values in a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns i
2 min read
Python | Pandas Series.mad() to calculate Mean Absolute Deviation of a Series
Pandas provide a method to make Calculation of MAD (Mean Absolute Deviation) very easy. MAD is defined as average distance between each value and mean. The formula used to calculate MAD is: Syntax: Series.mad(axis=None, skipna=None, level=None) Parameters: axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation. skipn
2 min read
Convert a series of date strings to a time series in Pandas Dataframe
During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized
3 min read
Convert Series of lists to one Series in Pandas
In this program, we will see how to convert a series of lists of into one series, in other words, we are just merging the different lists into one single list, in Pandas. We will be using the stack() method to perform this task. The line will be Series.apply(Pandas.Series).stack().reset_index(drop = True). The reset_index() method will reset the in
1 min read
Converting Series of lists to one Series in Pandas
Let us see how to convert a Series of lists to a single Series in Pandas. First of all let us create a Series of lists. For this problem we have created a Series of list having 12 elements, each list is of length 3 and there are 4 lists hence total elements are 12. When the Series of list will be converted to one it will have 12 elements. C/C++ Cod
2 min read
Pandas - Get the elements of series that are not present in other series
Sometimes we have two or more series and we have to find all those elements that are present in one series but not in other. We can do this easily, using the Bitwise NOT operator along with the pandas.isin() function. Example 1: Taking two Integer Series C/C++ Code # Importing pandas library import pandas as pd # Creating 2 pandas Series ps1 = pd.S
2 min read
Pandas Series dt.month | Extract Month Part From DateTime Series
The dt.month attribute returns a NumPy array containing the month of the DateTime in the underlying data of the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = id
2 min read
Pandas Series dt.day | Extract Day Part from DateTime Series
Pandas dt.day attribute returns a NumPy array containing the day value of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set th
2 min read
Pandas Series dt.week | Extract Week Number from DateTime Series
Pandas dt.week attribute returns a NumPy array containing the week ordinal of the year in the underlying data of the given DateTime Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.month_name() | Get Month Name From DateTime Series
Pandas dt.month_name() method returns the month names of the DateTimeIndex with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result = s
2 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Pandas Series dt.nanosecond | Get Nanoseconds From DateTime Series
Pandas dt.nanosecond attribute returns a NumPy array containing the nanosecond of the DateTime in the underlying data of the given series object.  Example C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = '5N')) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx result = sr.dt.nanose
2 min read
Pandas Series dt.tz_convert | Change Timezone in DateTime Series
The dt.tz_convert() method converts tz-aware DateTime Series object from one time zone to another. Example C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx result = sr.dt.tz_convert(tz = 'Europe / Berlin')
2 min read
three90RightbarBannerImg