加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在pandas数据帧中快速和高效地将两列(浮点)捕获到列中?

发布时间:2020-12-20 12:01:31 所属栏目:Python 来源:网络整理
导读:我想通过cat two column(float或int)得到一个新列,如下所示, 所以任何人都有更好的主意? 我认为我的事情太复杂了 a=pandas.Series([1,3,5,7,9])b=pandas.Series([2,4,6,8,10])c=pandas.Series([3,10])abc=pandas.DataFrame({'a':a,'b':b,'c':c})abc a b c0
我想通过cat two column(float或int)得到一个新列,如下所示,

所以任何人都有更好的主意?

我认为我的事情太复杂了

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,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,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

解决方法

使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读