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

标签 python pandas

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/

相关文章:

python - Pyspark - withColumn 在调用空数据框时不起作用

python - 使用 cython 和 C++ 访问结构中的 vector 的奇怪错误

python - 使用 Pandas 石斑鱼时如何取系列的最大值?

python - 是否可以将不同长度的列表作为空数据框中的列附加?

python - 减去数据框中的两列

python - 在 Pandas 数据框中提取嵌套的 JSON

python - 无效的URL给出regexmatchError并且在pytube程序中给出无效的URL时不引发错误

python - 如何查看Python的假设库的输出

python - 是否有可能使 Python 函数的行为像实例一样?

python - Pandas 。如何从 ZIP 存档中读取 Excel 文件