python - 使用条件语句用括号分隔以分隔列
问题描述
希望根据括号中的文本将文本拆分为列,并根据列中的字符串匹配进行分配。
原始内容的格式为:
文本 |
---|
(纽约时报)“战争新闻”(wsj)“商业新闻”(纽约时报)“更多新闻” |
寻找它来产生以下输出:
文本 | 纽约时报 | 华尔街日报 |
---|---|---|
(纽约时报)“与纽约时报的战争新闻”(wsj)“商业新闻”(纽约时报)“更多关于商品的新闻” | [“与纽约时报的战争新闻”,“更多新闻”] | [“商业新闻”] |
括号内的所有字符串都是已知的。我从这段代码开始,但不确定如何继续。不能简单地由新闻机构划定,而是在括号内。
df['nytimes'] = df['text'].apply(lambda text: [group for group in text.split(regex)])
解决方案
我相信可以更好地修改此代码。但它可以在没有循环的情况下完成工作
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()
推荐阅读
- python - 如何修复 Python 中的 Module not found 错误?
- mysql - 考虑到数据更改的 mysql 查询的复杂旋转将在未来使用 Mysql 作为 DB 发生
- python - 为什么从 R 中的 stats 包中的函数 fft 返回的常量在评估时不返回信号的近似值?
- ios - 信号量等待和信号是否应该总是从单独的队列中调用?
- javascript - 反应没有输出
- r - 如何将活动用户的电子邮件从 wordpress 站点传递到外部闪亮的 R 应用程序?
- azure - 如何获取触发 Azure 数据工厂管道的文件的名称?
- javascript - React 功能组件道具值未更新
- powershell - Zabbix server 'Action' 试图触发 Host Agent powershell - 不运行
- scala - 是否可以从 Akka Streams Flow 生成多个元素