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

2024-09-28 19:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)

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

我想创建一个数据框,在该数据框中,每个标签中具有特征值featureA_1, featureA_2, featureA_3的条目百分比以及每个标签中具有特征值featureB_1featureB_2的条目百分比。

我还想得到FeatureUrea值类型和featureB值类型百分比的标准偏差。

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

enter image description here

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


Tags: 数据方法标题示例编码标签labelcat
1条回答
网友
1楼 · 发布于 2024-09-28 19:25:30

使用:

#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  

相关问题 更多 >