将包含2个值的列拆分为pandas df中的不同列 [英] Split Column containing 2 values into different column in pandas df

查看:65
本文介绍了将包含2个值的列拆分为pandas df中的不同列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫df中有一张桌子

i have a table in pandas df

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

以此类推,直到50行.

and so on, till 50 rows.

我要寻找的是将 bigram 列拆分为两个不同的列,删除括号和逗号,例如

what i am looking for is, split the bigram column into two different columns removing the brackets and comma like,

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

如果用逗号分隔,是否有任何方法可以拆分并删除括号.

is there any way to split if after comma,and removing brackets.

推荐答案

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

If your bigram column happens to be string format, you can use .str.extract() method with regex to extract numbers from it:

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

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

Or if the bigram column is of tuple type:

Method1 :使用pd.Series从元组中创建列:

Method1: use pd.Series to create columns from the tuple:

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

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

Method2: use .str to get the first and second element from the tuple

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

这篇关于将包含2个值的列拆分为pandas df中的不同列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆