计算熊猫数据框中相似值的百分比


14

我有一个数据框df,有两列:脚本(带文本)和扬声器

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

我有以下列表: L = ['a','b','c']

使用以下代码,

df = (df.set_index('Speaker')['Script'].str.findall('|'.join(L))
        .str.join('|')
        .str.get_dummies()
        .sum(level=0))
print (df)

我得到这个数据框df2

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

我可以在代码中添加哪一行,以便为数据框的每一行获取df2讲话者说出的所有行的百分比值,以便具有以下数据框df3

Speaker     a    b    c
Speaker 1   50%  25%   25%
Speaker 2  100%    0   0
Speaker 3   0   100%   0

Answers:


8

您可以sum沿第一个轴除以,然后转换为字符串并添加%

out = (df.set_index('Speaker')['Script'].str.findall('|'.join(L))
         .str.join('|')
         .str.get_dummies()
         .sum(level=0))

(out/out.sum(0)[:,None]).mul(100).astype(int).astype(str).add('%')

            a     b    c
Speaker                  
Speaker1   50%   25%  25%
Speaker2  100%    0%   0%
Speaker3    0%  100%   0%

5

从原始数据帧开始,如果要使用%而不是虚拟的分组总和,则可以更改整个脚本,如下所示:

m = df.set_index('Speaker')['Script'].str.findall('|'.join(L)) #creates a list of matches
m = m.explode().reset_index() #explode to a series 
final = pd.crosstab(m['Speaker'],m['Script'],normalize='index').mul(100) # percentage pivot

Script         a      b     c
Speaker                      
Speaker 1   50.0   25.0  25.0
Speaker 2  100.0    0.0   0.0
Speaker 3    0.0  100.0   0.0

如果您不希望使用该百分比,请使用:

pd.crosstab(m['Speaker'],m['Script'])

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

注意:此版本使用pandas 0.25+版本


3
(df.set_index('Speaker')['Script'].str.extractall(f'({"|".join(L)})')
   .groupby('Speaker')[0].value_counts(normalize=True)
   .unstack(fill_value=0)
)

输出:

0            a     b     c
Speaker                   
Speaker 1  0.5  0.25  0.25
Speaker 2  1.0  0.00  0.00
Speaker 3  0.0  1.00  0.00

2

给定示例,您可以尝试以下代码行:

df = (df/df.sum(axis=1)[:, None]).mul(100).astype(int)

使用您提供的数据:

import pandas as pd
import numpy as np
data = {'a':[2,2,0],'b':[1,0,1],'c':[1,0,0]}
df = pd.DataFrame(data)
df = (df/df.sum(axis=1)[:, None]).mul(100).astype(int)
print(df)

输出:

     a   b   c
0   50  25  25
1  100   0   0
2    0 100   0

或者,如果您想添加'%'符号:

df = (df / df.sum(axis=1)[:, None]).mul(100).astype(int).astype(str) + '%'

输出:

      a     b    c
0   50%   25%  25%
1  100%    0%   0%
2    0%  100%   0%
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.