Skip to main content
 首页 » 编程设计

python之根据另一列中的值规范化 Pandas 数据框中的列

2025年05月04日35jillzhang

我想根据另一列中的值对 pandas 数据框的一列中的值进行归一化。这不是统计意义上的纯粹标准化。第二个值是类型;我想对每种类型的所有第一个值求和,然后在每一行中,将该值除以该行类型的总数。举个例子应该可以更清楚地说明这一点。

df = pd.read_table(datafile, names = ["A", "B", "value", "type"]) 
 
    A   B  value   type 
0  A1  B1      1  type1 
1  A2  B2      1  type1 
2  A1  B1      1  type2 
3  A1  B3      1  type3 
4  A2  B2      1  type2 
5  A2  B4      1  type3 
6  A3  B4      1  type2 
7  A3  B5      1  type3 
8  A4  B6      1  type2 
9  A4  B7      1  type3 

然后我可以用类似的东西找到总和:

types = df.groupby(["type"])["value"].sum() 
 
type 
type1    2 
type2    4 
type3    4 
Name: value, dtype: int64 

那我该如何使用它来规范化每行中的值呢?

我可以使用这样的循环来计算归一化值:

norms = [] 
for ix, row in df.iterrows(): 
    norms.append(row["value"]/types[row["type"]]) 

然后用具有这些值的新列替换该列:

df["value"] = pd.Series(norms) 
 
    A   B  value   type 
0  A1  B1   0.50  type1 
1  A2  B2   0.50  type1 
2  A1  B1   0.25  type2 
3  A1  B3   0.25  type3 
4  A2  B2   0.25  type2 
5  A2  B4   0.25  type3 
6  A3  B4   0.25  type2 
7  A3  B5   0.25  type3 
8  A4  B6   0.25  type2 
9  A4  B7   0.25  type3 

但据我所知,使用这样的循环不是很有效或不合适,并且可能有一种方法可以使用一些标准的 pandas 函数来实现。

谢谢。

请您参考如下方法:

您可以使用 transform,它对每个组执行操作,然后扩展结果以匹配原始索引。例如"

>>> df["value"] /= df.groupby("type")["value"].transform(sum) 
>>> df 
    A   B  value   type 
0  A1  B1   0.50  type1 
1  A2  B2   0.50  type1 
2  A1  B1   0.25  type2 
3  A1  B3   0.25  type3 
4  A2  B2   0.25  type2 
5  A2  B4   0.25  type3 
6  A3  B4   0.25  type2 
7  A3  B5   0.25  type3 
8  A4  B6   0.25  type2 
9  A4  B7   0.25  type3 

因为我们有

>>> df.groupby("type")["value"].transform(sum) 
0    2 
1    2 
2    4 
3    4 
4    4 
5    4 
6    4 
7    4 
8    4 
9    4 
dtype: int64