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

python – 包含2个值的拆分列到pandas df中的不同列中

发布时间:2020-12-20 11:55:52 所属栏目:Python 来源:网络整理
导读:我有一张pandas df的桌子 bigram frequency(123,3245) 2(676,35346) 84(93,32) 9 等等,直到50行. 我正在寻找的是,将bigram列分成两个不同的列,删除括号和逗号, col1 col2 frequency123 3245 2676 35346 8493 32 9 是否有任何方法可以在逗号之后拆分,并删除括
我有一张pandas df的桌子

bigram         frequency
(123,3245)       2
(676,35346)      84
(93,32)          9

等等,直到50行.

我正在寻找的是,将bigram列分成两个不同的列,删除括号和逗号,

col1     col2      frequency
123       3245        2
676       35346       84
93        32          9

是否有任何方法可以在逗号之后拆分,并删除括号.

解决方法

如果您的bigram列恰好是字符串格式,则可以使用带有正则表达式的.str.extract()方法从中提取数字:

pd.concat([df.bigram.str.extract('(?P<col1>d+),(?P<col2>d+)'),df.frequency],axis = 1)

enter image description here

或者如果bigram列是元组类型:

方法1:使用pd.Series从元组创建列:

pd.concat([df.bigram.apply(lambda x: pd.Series(x,index=['col1','col2'])),axis=1)

方法2:使用.str从元组中获取第一个和第二个元素

df['col1'],df['col2'] = df.bigram.str[0],df.bigram.str[1]
df = df.drop('bigram',axis=1)

(编辑:李大同)

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

    推荐文章
      热点阅读