How to Concatenate Strings from Two Pandas Columns?

Patricia Arquette
Release: 2024-11-22 05:01:15
Original
378 people have browsed it

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]})
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template