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.
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 |
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!