如何在pandas数据框中快速有效地将两列(float)合并为一列?

3
我想通过连接两个列(float或int)来创建一个新列,如下所示:
你有更好的想法吗?
我觉得我的方法太过复杂了。
a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
3个回答

3

使用astype方法将数据类型转换为str

#if need select columns by position with iloc
abc['new'] = abc.iloc[:,0].astype(str) + '::' + abc.iloc[:,1].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

#if need select by column names
abc['new'] = abc['a'].astype(str) + '::' + abc['b'].astype(str)
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

使用str.cat解决方案:

abc['new'] = abc['a'].astype(str).str.cat(abc['b'].astype(str), sep='::')
print (abc)
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

3
您也可以使用map来执行类似的操作。
abc['d'] = abc['a'].map(str) +'::'+ abc['b'].map(str)
print(abc)

输出:

   a   b   c      d
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

1
如何使用 apply
abc['new'] = abc.apply(lambda x: '{}::{}'.format(x['a'],x['b']), axis=1)

这是一个简单的一行代码,写法如下。

谢谢你的回答,但Rayhane Mama可能是最简单的解决方案。 - cwind
是的,但请注意它对数据进行了3次迭代(“map”,“map”和赋值)。 - Dimgold
1
apply 函数运行缓慢,或许可以参考这个链接 - Jeff 现在是 pandas 的开发者。 - jezrael
对我来说是个难题,但我认为 map 更简单更快。但 apply 更复杂。另外,如果使用 .apply(axis=1),它会按行处理,速度也很慢。对于你的解决方案,不能使用 map,因为它只能用于一个列(Series)。 - jezrael
同时也可以看到完美的maxu答案,并比较解决方案 - https://dev59.com/D2Ik5IYBdhLWcg3wU8yo#36911306 - jezrael
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接