gpt4 book ai didi

python - 如果满足特定条件,则对列求和并替换各个值

转载 作者:行者123 更新时间:2023-12-01 00:05:50 25 4
gpt4 key购买 nike

import pandas

d = {'col1': [25,20,30],
'col2': [25,20,30],
'col3': [25,20,30],
'col4': [25,39,11]
}

df = pandas.DataFrame(data=d)

我如何从此数据帧循环并添加 col1 + col2 + col3 + col4,如果不等于 100,则在该索引中取值执行此 col1/(col1+col2+col3+col4 并将其作为新值这样,当您对 col1 + col2 + col3 + col4 求和时,该索引的总和就是 100。

例如,对于索引 0,当您添加 col1 + col2 + col3 + col4 时,它等于 100,因此,转到下一个索引,但是对于索引 1,它加起来为 99,因此取 20/99 并将其设为该位置的新值等。

预期输出:


d = {'col1': [25,20/99,30/101],
'col2': [25,20/99,30/101],
'col3': [25,20/99,30/101],
'col4': [25,39/99,11/101]
}

df = pandas.DataFrame(data=d)

最佳答案

这是一个矢量化版本:

c = df.sum(1).ne(100)
vals = np.where(c[:,None],df.div(df.sum(1),axis=0),df)
new_df = pd.DataFrame(vals,index=df.index,columns=df.columns)
# for overwriting the original df , use: df[:] = vals
print(new_df)
<小时/>
       col1      col2      col3       col4
0 25.00000 25.00000 25.00000 25.000000
1 0.20202 0.20202 0.20202 0.393939
2 0.29703 0.29703 0.29703 0.108911

关于python - 如果满足特定条件,则对列求和并替换各个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59990696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com