Python 将数据帧与一种热编码编码进行比较
我有两个数据帧(比如Python 将数据帧与一种热编码编码进行比较,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个数据帧(比如df1和df2) 在df1中,我有一个标题为“label”的列,它表示唯一的标签值。df1中没有两行具有相同的“标签”值。它有三列标题分别为featureA_1、featureA_2、featureA_3,每个列都包含浮点值。这些列表示featureA的可能特征值。类似地,此数据框还有两列,标题为featureB_1和featureB_2,其中包含浮点值,并表示featureB的唯一特征值。此外,它有两列,其中包含featureurea和featureB属性值的标准偏差。它们
df1
和df2
)
在df1
中,我有一个标题为“label”
的列,它表示唯一的标签值。df1
中没有两行具有相同的“标签”
值。它有三列标题分别为featureA_1、featureA_2、featureA_3
,每个列都包含浮点值。这些列表示featureA
的可能特征值。类似地,此数据框还有两列,标题为featureB_1
和featureB_2
,其中包含浮点值,并表示featureB
的唯一特征值。此外,它有两列,其中包含featureurea
和featureB
属性值的标准偏差。它们的标题为feature\u std
和featureB\u std
以下是df1
的示例
df1
可以使用以下代码段创建:
dict1 = {
"label": ["cat", "dog"],
"featureA_1": [0.60, 0.67],
"featureA_2": [0.20, 0.00],
"featureA_3": [0.20, 0.33],
"featureA_std": [0.189, 0.274],
"featureB_1": [0.40, 0.67],
"featureB_2": [0.60, 0.33],
"featureB_std": [0.10, 0.17],
}
df1 = pd.DataFrame(dict1)
在df2
中,除了标准偏差列之外,我的列与df1
相同。在这里,标题为“label”
的列可以有多个具有相同字符串值的值。这里的每一行代表一个样本。featureA\u 1、featureA\u 2、featureA\u 3的值表示featureA
的一个热编码值。和featureB_1
和featureB_2
表示featureB的一个热编码值。
由于有一个热编码,上述数据帧中的每一行将只有featureA_1、featureA_2、featureA_3中的一个特征值的值1,其他的值为0。类似地,每行的特征值featureB_1和featureB_2中只有一个为1,另一个为0
以下是df2的示例。
df2
可以使用以下代码段创建
dict2 = {
"label": ["cat", "cat", "dog"],
"featureA_1": [1, 0, 0],
"featureA_2": [0, 1, 0],
"featureA_3": [0, 0, 1],
"featureB_1": [0, 0, 1],
"featureB_2": [1, 1, 0],
}
df2 = pd.DataFrame(dict2)
我想将df2
的每一行与df1
进行比较,找到featureA
的值(即featureA_1
,featureA_2
,featureA_3
),该值对应于df2
中值为1的相应列。我想将相应的标准偏差(即featureA\u std
列)除以该值。我想为功能B做同样的练习。
也一样。
以下是我期望输出数据帧的外观:
我的帖子遵循的方法很少,但提出了不同的问题
如何实现这一点?思想是在多索引的第一级将列名称拆分为\uu
并除以以下值后,将带有std
的列转换为dfstd
,以匹配df22
:
是否可以在文本中创建df2
?我得到了不同的数字。耶兹雷尔:现在检查数值。@Commoner-因为1/0.189=5.291005
,如果理解正确需要什么,谢谢你的回答。我的意思是标准偏差除以df1中包含的相应列。我正在用正确的值更新最终数据帧的图片。Jezrael:下面是最终数字中的数字是如何获得的:0.189/0.6=0.315
,0.189/0.2=0.945
,0.274/0.33=0.8303
,0.1/0.6=0.1667
,0.17/0.67=0.253
。
df1 = df1.set_index('label')
df2 = df2.set_index('label')
dfstd = df1.filter(like='std')
dfstd.columns = dfstd.columns.str.replace('_std','')
print (dfstd)
featureA featureB
label
cat 0.189 0.10
dog 0.274 0.17
df11 = df1.copy()
df11.columns = df11.columns.str.split('_', expand=True)
print (df11)
featureA featureB
1 2 3 std 1 2 std
label
cat 0.60 0.2 0.20 0.189 0.40 0.60 0.10
dog 0.67 0.0 0.33 0.274 0.67 0.33 0.17
df = df11.div(dfstd, level=0)
df.columns = df.columns.map('_'.join)
print (df)
featureA_1 featureA_2 featureA_3 featureA_std featureB_1 \
label
cat 3.174603 1.058201 1.058201 1.0 4.000000
dog 2.445255 0.000000 1.204380 1.0 3.941176
featureB_2 featureB_std
label
cat 6.000000 1.0
dog 1.941176 1.0
df2 = df2.div(df).dropna(how='all', axis=1).fillna(0)
print (df2)
featureA_1 featureA_2 featureA_3 featureB_1 featureB_2
label
cat 0.315 0.000 0.000000 0.000000 0.166667
cat 0.000 0.945 0.000000 0.000000 0.166667
dog 0.000 0.000 0.830303 0.253731 0.000000