简体   繁体   English

合并两列数据框的值与不同的dtypes

[英]Merging values of two columns of dataframe with different dtypes

I have the following pandas dataframe : 我有以下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 : 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: 我正在寻找一种合并系列df["chain"]df["pos"]来实现以下目标:

   chain+pos
0     A1
1     B2
2     C3

and df.dtypes : 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. MaxU的解决方案非常有效。 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. 在此之后,您必须删除df ['chain']和df ['pos']以获得所需的结果。

----------------- Edit -----------------编辑

As @MaxU pointed out in his comment below, here is a concise way of achieving the desired result - 正如@MaxU在下面的评论中所指出的,这是一种实现理想结果的简洁方法 -

df['chain+pos'] = df.pop('chain') + df.pop('pos').map(str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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