复杂的分隔和分组以显示百分比(Pandas/Python)



困境:

我有一个数据集df,我想在其中用一种复杂的格式在一个特定的列中进行分离和分组,并显示百分比。我通过关注前三个"单词"(例如(来分隔Type列中的值Hello HEL HE-和后面跟着字母T-12T的值

There are    3  unique counts    of   Hello-HEL-HE-A6123-123A-12T
2  unique counts    of   Hello-HEL-HE-A6123-123A-50T
1  unique count(s)  of   Happy-HAP-HA-R650-570A-90T    

数据:

Type                                    Value
Hello-HEL-HE-A6123-123A-12T_TYPE-v.A    1,111,111
Hello-HEL-HE-A6123-123A-12T_TYPE-v.B    111,111
Hello-HEL-HE-A6123-123A-12T_TYPE-v.E    2,345,667
Hello-HEL-HE-A6123-123A-50T_TYPE-v.C    222,334
Hello-HEL-HE-A6123-123A-50T_TYPE-v.A    89
Happy-HAP-HA-R650-570A-90T_version-v.A  6

所需输出:

Type                                    Percent
Hello-HEL-HE-12T                        50%
Hello-HEL-HE-50T                        33%
Happy-HAP-HA-90T                      16.6%

执行:

(建议在"_"上拆分,然后在"-"上拆分(

df.str.split(pat="_")                                      #separating by hyphen
(df['Type'].value_counts(normalize=True) * 100).to_frame()  #groupby

然而,我不知道如何通过:你好,HEL HE以及-12T 来区分每种类型

欢迎任何建议

让我们试试

df=df.assign(Value=df['Value'].str.split(','),Type=df.Type.str.split('_').str[0])
df2=(df['Type'].value_counts(normalize=True)*100).to_frame('%')
df2.rename_axis(index='Type')


%
Type                                  
Hello-HEL-HE-A6123-123A-12T  50.000000
Hello-HEL-HE-A6123-123A-50T  33.333333
Happy-HAP-HA-R650-570A-90T   16.666667

您可以执行以下操作:

df['Type'].str.split('_').str[0].value_counts(normalize=True)
Hello-HEL-HE-A6123-123A-12T    0.500000
Hello-HEL-HE-A6123-123A-50T    0.333333
Happy-HAP-HA-R650-570A-90T     0.166667

如果你想要特定的表格,那么:

tmp = df['Type'].str.split('_').str[0].value_counts(normalize=True).reset_index(name='percentage').rename(columns={'index': 'Type'})
tmp['percentage'] = tmp['percentage'].apply(lambda x: '{:.2f}%'.format(100*x))
tmp
Type percentage
Hello-HEL-HE-A6123-123A-12T     50.00%
Hello-HEL-HE-A6123-123A-50T     33.33%
Happy-HAP-HA-R650-570A-90T     16.67%

如果要获取下划线之前的所有字段:

key = df.Type.str.split(r'_', n=1, expand=True)[0]
key
# out:
0    Hello-HEL-HE-A6123-123A-12T
1    Hello-HEL-HE-A6123-123A-12T
2    Hello-HEL-HE-A6123-123A-12T
3    Hello-HEL-HE-A6123-123A-50T
4    Hello-HEL-HE-A6123-123A-50T
5     Happy-HAP-HA-R650-570A-90T

如果你想要前三个单词,最后一个在下划线之前,那么:

a = df.Type.str.split(r'_', n=1, expand=True)[0].str.split(r'-', expand=True)
sel = list(a.columns)
sel = sel[1:3] + sel[-1:]
key = a[0].str.cat(a[sel], '-')
key
# out:
0    Hello-HEL-HE-12T
1    Hello-HEL-HE-12T
2    Hello-HEL-HE-12T
3    Hello-HEL-HE-50T
4    Hello-HEL-HE-50T
5    Happy-HAP-HA-90T

在任何一种情况下,您都可以按该键分组:

cnt = df.groupby(key)['Value'].count()
100 * cnt / cnt.sum()
# out:
Happy-HAP-HA-90T    16.666667
Hello-HEL-HE-12T    50.000000
Hello-HEL-HE-50T    33.333333

最新更新