2017-08-30 29 views
2

通过R,我可以很容易地从字符串列表中创建一个包含某些字符串模式的频率的数据帧。统计数据帧中字符串的出现

library(stringr) 
library(tm) 
library(dplyr)  
text = c('i am so hhappy happy now','you look ssad','sad day today','noway') 
dat = sapply(c('happy', 'sad'), function(i) str_count(text, i)) 
dat = data.frame(dat) 
dat = dat %>% mutate(Sentiment = (happy)-(sad)) 

其结果是,我能有这样的

happy sad Sentiment 
1  2 0   2 
2  0 1  -1 
3  0 1  -1 
4  0 0   0 

Python中的数据帧,我可以假设代码的其余部分除sapply()

import pandas as pd 
text = ['i am so hhappy happy now','you look ssad','sad day today','noway'] 
???? 
dat = pd.DataFrame(dat) 
dat['Sentiment'] = dat.apply(lambda c: c.happy - c.sad) 

什么会????是什么?

回答

4

你可以使用pd.Series.str.count

import pandas as pd 
import numpy as np 

text = ['i am so hhappy happy now','you look ssad','sad day today','noway'] 
df = pd.DataFrame({'text' : text}) 

df['happy'] = df.text.str.count('happy') 
df['sad'] = df.text.str.count('sad') 
df['Sentiment'] = df.happy - df.sad 

df  
         text happy sad Sentiment 
0 i am so happy happy now  2 0   2 
1    you look sad  0 1   -1 
2   sad day today  0 1   -1 
3     noway  0 0   0 
+0

而且,只是为了更详细信息,您可以构造'从'text'列表上方df'做'DF = pd.DataFrame([句子]对于文本中的句子],columns = ['text'])' – Paul

+0

@Paul有一种更简单的方法。 ;-) –

+0

啊,确实有!我可能应该想到这一点。感谢您添加它。 – Paul

相关问题