【发布时间】:2020-05-16 08:15:57
【问题描述】:
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)
【问题讨论】:
-
请也添加预期的输出(类似于输入数据框)
-
为什么不将
25/99划分为索引1? -
因为 25+25+25+25 = 100,所以它基于索引而不是列中的值