简体   繁体   English

Str 包含来自列表并通过列表项区分

[英]Str contains from list and distinguish by items of list

I have one dataframe df , with two columns : Script (with text) and Speaker我有一个数据框df ,有两列:脚本(带文本)和扬声器

Script  Speaker
aze     Speaker 1 
art     Speaker 2
ghb     Speaker 3
jka     Speaker 1
tyc     Speaker 1
avv     Speaker 2 
bhj     Speaker 1

And I have the folloing list : list = ['a','b','c']我有以下列表: list = ['a','b','c']

My target is to obtain a matrix/dataframe like this, only with items from my list.我的目标是获得这样的矩阵/数据框,只有我列表中的项目。

Speaker     a    b    c
Speaker 1   2    1    1
Speaker 2   2    0    0
Speaker 3   0    1    0

I tried the following :我尝试了以下方法:

r = '|'.join(list)

nb_df = df[df['Script'].str.contains(r, case = False)]
df_target = nb_df.groupby('Speaker')['Speaker'].count()

I obtain a part of my target, I know how much time each speaker say items searched from list.我获得了目标的一部分,我知道每个发言者说从列表中搜索的项目的时间。 but I can't distinguish the number of time for each of the items.但我无法区分每个项目的时间数。

  1. How can I make it with a pandas function (if existing)如何使用 Pandas 函数(如果存在)
  2. How could I make it with a Python Loop ?我怎么能用 Python 循环呢?

First not use list like variable, because builtin (python code word).首先不要像变量一样使用list ,因为内置(python 代码字)。

Use crosstab with Series.str.extractall :crosstabSeries.str.extractall一起Series.str.extractall

print (df)
  Script    Speaker
0    azc  Speaker 1 <-change sample data
1    art  Speaker 2
2    ghb  Speaker 3
3    jka  Speaker 1
4    tyc  Speaker 1
5    avv  Speaker 2
6    bhj  Speaker 1

L = ['a','b','c']
pat = r'({})'.format('|'.join(L))
df = df.set_index('Speaker')['Script'].str.extractall(pat)[0].reset_index(name='val')

df = pd.crosstab(df['Speaker'], df['val'])
print (df)
val        a  b  c
Speaker           
Speaker 1  2  1  2
Speaker 2  2  0  0
Speaker 3  0  1  0

If performance is not so important use 3 text functions Series.str.findall , Series.str.join and Series.str.get_dummies and sum per level:如果性能不是那么重要,请使用 3 个文本函数Series.str.findallSeries.str.joinSeries.str.get_dummies并按级别sum

df = (df.set_index('Speaker')['Script'].str.findall('|'.join(L))
        .str.join('|')
        .str.get_dummies()
        .sum(level=0))
print (df)
           a  b  c
Speaker           
Speaker 1  2  1  2
Speaker 2  2  0  0
Speaker 3  0  1  0

You can use the series.str.findall() with str.join() and str.get_dummies() with groupby().sum :您可以将series.str.findall()str.join()str.get_dummies()groupby().sum

l = ['a','b','c']
final=(df['Script'].str.findall('|'.join(l)).str.join('|')
  .str.get_dummies().groupby(df['Speaker']).sum())

           a  b  c
Speaker           
Speaker 1  2  1  1
Speaker 2  2  0  0
Speaker 3  0  1  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM