Home  >  Article  >  Backend Development  >  How to Concatenate Strings from Two Pandas Columns?

How to Concatenate Strings from Two Pandas Columns?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-22 05:01:15387browse

How to Concatenate Strings from Two Pandas Columns?

String Concatenation of Two Pandas Columns

When working with pandas DataFrames, it's often necessary to combine data from different columns to create new values. One common task is to concatenate strings from two or more columns.

The Problem

Given a DataFrame with two columns, 'bar' and 'foo':

df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

we aim to create a new column that concatenates the values of 'bar' and 'foo' as follows:

bar foo New Column
1 a 1 is a
2 b 2 is b
3 c 3 is c

The Answer

To achieve this, we can use the map() function to convert the 'bar' column to strings and then concatenate it with the 'foo' column using the operator:

df['bar'] = df.bar.map(str) + " is " + df.foo

Here, the map() function is used to apply the string conversion to each element of the 'bar' column. The resulting column is then concatenated with the 'foo' column using the operator.

The updated DataFrame will now contain the desired string concatenation:

bar foo New Column
1 a 1 is a
2 b 2 is b
3 c 3 is c

The above is the detailed content of How to Concatenate Strings from Two Pandas Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn