首页 > 解决方案 > 使用条件语句用括号分隔以分隔列

问题描述

希望根据括号中的文本将文本拆分为列,并根据列中的字符串匹配进行分配。

原始内容的格式为:

文本
(纽约时报)“战争新闻”(wsj)“商业新闻”(纽约时报)“更多新闻”

寻找它来产生以下输出:

文本 纽约时报 华尔街日报
(纽约时报)“与纽约时报的战争新闻”(wsj)“商业新闻”(纽约时报)“更多关于商品的新闻” [“与纽约时报的战争新闻”,“更多新闻”] [“商业新闻”]

括号内的所有字符串都是已知的。我从这段代码开始,但不确定如何继续。不能简单地由新闻机构划定,而是在括号内。

df['nytimes'] = df['text'].apply(lambda text: [group for group in text.split(regex)])

标签: pythonpandas

解决方案


我相信可以更好地修改此代码。但它可以在没有循环的情况下完成工作

texts= ['(nytimes) "news on war" (wsj) "news on business" (nytimes) "more news"']

data = pd.DataFrame(texts,columns=['text'])
#use extract all to identify selected texts
new= data['text'].str.extractall(r'((?:\(\w+\)."\w+.\w+ \w+?"))')

#extractall will create a multi index columns, and so you need to adjust it

new_1= new.droplevel(level=1)
val = new_1[0].explode()[0].str.split().str[0]
val2 = new_1[0].explode()[0].str.split().str[1:].apply(lambda x: ' '.join(x))

#Created the new DataFrame to better do some cleaning and grouping earlier results
cleaner  = pd.DataFrame()
cleaner['one']= val
cleaner['two']= val2

cleaner =cleaner.groupby('one').aggregate(lambda tdf: tdf.unique().tolist()).reset_index().T
#cleaner.columns= ['NyTimes','WSJ']

cleaner.reset_index(inplace=True)
cleaner.drop(0,axis=0,inplace=True)
cleaner.drop('index',axis=1,inplace=True)

#once the data is is clean to expectation, include it back to main data.
data[['NyTimes','WSJ']]= cleaner.values
data.head()

推荐阅读