I have the following pandas dataframe
:
import pandas as pd
df = pd.DataFrame({"pos": [1, 2, 3], "chain": ["A", "B", "C"]})
Giving:
chain pos
0 A 1
1 B 2
2 C 3
and df.types
:
chain object
pos int64
dtype: object
I'm looking for a way to merge Series df["chain"]
and df["pos"]
to have the following:
chain+pos
0 A1
1 B2
2 C3
and df.dtypes
:
chain+pos object
dtype: object
Is there an easy way to do it?
df.astype(str).sum(1)
Out[489]:
0 A1
1 B2
2 C3
dtype: object
In [34]: df['chain'] += df.pop('pos').astype(str)
In [35]: df
Out[35]:
chain
0 A1
1 B2
2 C3
renaming column:
In [37]: df = df.rename(columns={'chain':'chain+pos'})
In [38]: df
Out[38]:
chain+pos
0 A1
1 B2
2 C3
The solution by MaxU works very well. Otherwise you can use the following also
df["chain+pos"] = df['chain'] + df['pos'].map(str)
After this, you have to drop df['chain'] and df['pos'] to attain the desired result.
----------------- Edit
As @MaxU pointed out in his comment below, here is a concise way of achieving the desired result -
df['chain+pos'] = df.pop('chain') + df.pop('pos').map(str)
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.