简体   繁体   中英

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')

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

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

Here is a possible solution:

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

You can use:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM