1 回答
TA贡献1830条经验 获得超3个赞
df.assign(mean = df[["a", "b"]].mean(axis=1))\
.assign(mean = df["mean"].subtract(df.groupby("mean").cumcount().divide(10)))
输出
# Name Sum a b mean
# 0 hamm 34 2 2 2.0
# 1 jam 54 1 1 1.0
# 2 tan 36 3 1 1.9
# 3 pan 39 4 4 4.0
说明:
完整代码+插图
# Step 1
df["mean"] = df[["a", "b"]].mean(axis=1)
print(df)
# Name Sum a b mean
# 0 hamm 34 2 2 2.0
# 1 jam 54 1 1 1.0
# 2 tan 36 3 1 2.0
# 3 pan 39 4 4 4.0
# Step 2.1 + 2.2
print(df.groupby("mean").cumcount())
# 0 0
# 1 0
# 2 1
# 3 0
# dtype: int64
# Step 2.3
print(df.groupby("mean").cumcount().divide(10))
# 0 0.0
# 1 0.0
# 2 0.1
# 3 0.0
# dtype: float64
# Step 3
df["mean"] = df["mean"].subtract(df.groupby("mean").cumcount().divide(10))
print(df)
# Name Sum a b mean
# 0 hamm 34 2 2 2.0
# 1 jam 54 1 1 1.0
# 2 tan 36 3 1 1.9
# 3 pan 39 4 4 4.0
添加回答
举报