Pandas combine two strings ignore nan values

Given a pandas dataframe, we have to combine two strings while ignoring nan values.
Submitted by Pranit Sharma, on November 21, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Combining two strings ignore nan values

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

The string is a data type that can be added or concatenated i.e., we can simply join two strings using a + sign.

For example, we have two strings 'ab' and 'cd' and if we concatenate them they will become 'abcd'.

Since all the elements of all the columns in dataframe are string type, we will use the sum method along the row by passing the parameter (axis=1).

Let us understand with the help of an example,

Python code to combine two strings ignore nan values

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {

# Creating dataframe
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# adding columns of string type
df['New'] = df.fillna('').sum(axis=1)

# Display new df
print("New DataFrame:\n",df)


Example: Pandas combine two strings ignore nan values

Python Pandas Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.