pandas 数据帧中一个热编码列的统计信息

Ros*_*oss 5 python dataframe pandas

我有一个 Pandas 数据框,其中有一列名为"label". 它有三列featureA_1, featureA_2, featureA_3分别命名。这些列代表代表一个热编码值的列featureA(可以有三个唯一值。)同样,它也有两列分别标题为featureB_1featureB_2。这些列代表一个热编码值featureB(可以有两个不同的值。)

以下是所述数据框的示例

.

可以使用以下方法生成上述数据帧:

import pandas as pd
dictt = {
    "label": ["cat", "cat", "cat", "cat", "cat", "dog", "dog", "dog"],
    "featureA_1": [1, 0, 1, 1, 0, 1, 1, 0],
    "featureA_2": [0, 1, 0, 0, 0, 0, 0, 0],
    "featureA_3": [0, 0, 0, 0, 1, 0, 0, 1],
    "featureB_1": [0, 0, 1, 1, 0, 0, 1, 1],
    "featureB_2": [1, 1, 0, 0, 1, 1, 0, 0],
}

df1 = pd.DataFrame(dictt)
Run Code Online (Sandbox Code Playgroud)

由于一种热编码,上述数据帧中的每一行将仅对一个特征值具有值 1,featureA_1, featureA_2, featureA_3对其他特征值具有值0。类似地,每一行将具有值1只为一个的特征值的featureB_1featureB_2,并为其他零。

我想创建一个数据框,其中我将拥有每个标签中具有特征值featureA_1, featureA_2, featureA_3的条目百分比和每个标签中具有特征值featureB_1featureB_2.

我还想获得 featureA 值类型和 featureB 值类型的那些百分比的标准偏差。

以下是我希望拥有的数据框示例:

在此处输入图片说明

这样做的最有效方法是什么?在我的实际工作中,我将拥有数百万行的数据框。

jez*_*ael 2

使用:

#aggregate mean for percentages of 1, because only 0, 1 values 
df = df1.groupby('label').mean().add_suffix('_perc').round(2)

#aggregate std witg ddof=0, because default pandas ddof=1
df2 = df.groupby(lambda x: x.split('_')[0], axis=1).std(ddof=0).add_suffix('_std').round(2)

#join together
df = pd.concat([df, df2],axis=1).sort_index(axis=1).reset_index()
print (df)
  label  featureA_1_perc  featureA_2_perc  featureA_3_perc  featureA_std  \
0   cat             0.60              0.2             0.20          0.19   
1   dog             0.67              0.0             0.33          0.27   

   featureB_1_perc  featureB_2_perc  featureB_std  
0             0.40             0.60          0.10  
1             0.67             0.33          0.17  
Run Code Online (Sandbox Code Playgroud)