Ashwin Geet D'Sa
Ashwin Geet D'Sa

Reputation: 7379

Concat two columns values of dataframe

I have a dataframe as below:

     Name  Age
0    Alex   10
1     Bob   12
2  Clarke   13

The dataframe is created as:

data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])

I want to perform string concatenation of the two columns as:

     Name      Age
0    10 Alex   10 
1    12 Bob    12 
2    13 Clarke 13 

I tried using df["Name"] = df["Age"]+" "+df["Name"], which resulted in the below error:

Traceback (most recent call last): File "", line 1, in File "/anaconda3/envs/env1/lib/python3.6/site-packages/pandas/core/ops/common.py", line 65, in new_method return method(self, other) File "/anaconda3/envs/env1/lib/python3.6/site-packages/pandas/core/ops/init.py", line 343, in wrapper result = arithmetic_op(lvalues, rvalues, op) File "/anaconda3/envs/env1/lib/python3.6/site-packages/pandas/core/ops/array_ops.py", line 189, in arithmetic_op res_values = na_arithmetic_op(lvalues, rvalues, op) File "/anaconda3/envs/env1/lib/python3.6/site-packages/pandas/core/ops/array_ops.py", line 149, in na_arithmetic_op result = masked_arith_op(left, right, op) File "/anaconda3/envs/env1/lib/python3.6/site-packages/pandas/core/ops/array_ops.py", line 111, in masked_arith_op result[mask] = op(xrav[mask], y) numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')

Upvotes: 4

Views: 15640

Answers (5)

You can use:

df['Name']=df['Age'].apply(lambda x :str(x)) + ' ' + df['Name']

Upvotes: 2

Amandeep Singh
Amandeep Singh

Reputation: 385

We can use the apply function to cast the dataframe "age" column to string from int and then concatenate it to the "name" column using the "+" operator.

df["name"] = df["age"].apply(str) + " " + df["name"]

df["name"]

The output will look something like this

0      10 Alex
1      12 Bob
2      13 Clarke

Upvotes: 1

ansev
ansev

Reputation: 30940

Series.str.cat

df['Name'] = df['Age'].astype(str).str.cat(df['Name'], sep=' ')

        Name  Age
0    10 Alex   10
1     12 Bob   12
2  13 Clarke   13

Upvotes: 4

Riccardo Bucco
Riccardo Bucco

Reputation: 15384

Here is a possible solution:

df['Name'] = df['Age'].map(str) + ' ' + df['Name']

Upvotes: 2

Mayank Porwal
Mayank Porwal

Reputation: 34086

Since Age is an int column, you need to cast it to str using astype

In [2511]: df['Name'] = df["Age"].astype(str) + " " + df["Name"]

In [2511]: df['Name']
Out[2511]: 
0      10 Alex
1       12 Bob
2    13 Clarke

Upvotes: 11

Related Questions