【问题标题】:Pandas add row for each cell where function is applied to that specific cell while other element of new row are equal to starting rowPandas 为每个单元格添加行,其中函数应用于该特定单元格,而新行的其他元素等于起始行
【发布时间】:2023-01-23 19:04:05
【问题描述】:
我想遍历 pandas 数据帧行的每个元素,以便只有该元素被强调(即:它乘以 10%),而该行的其他元素保持相等。
我打算用它来进行敏感性分析。
例子:
df = pd.DataFrame({'AGE':[5,10],'POP':[100,200]})
最终期望的输出:
| AGE |
POP |
| 5 |
100 |
| 10 |
200 |
| 5*1.1 |
100 |
| 5 |
100*1.1 |
| 10*1.1 |
200 |
| 10 |
200*1.1 |
【问题讨论】:
标签:
python
pandas
dataframe
concatenation
nested-loops
【解决方案1】:
您可以使用交叉 merge 和 concat:
pd.concat([df,
(df.merge(pd.Series([1.1, 1], name='factor'), how='cross')
.pipe(lambda d: d.mul(d.pop('factor'), axis=0))
)], ignore_index=True)
输出:
AGE POP
0 5.0 100.0
1 10.0 200.0
2 5.5 110.0
3 5.0 100.0
4 11.0 220.0
5 10.0 200.0
【解决方案2】:
如果您有 2 列,则可以乘以 [1, stress] 并反转这些列,在排序时连接它们以保留相乘的列顺序。最后,还要添加原始帧:
stress = 1.1
factor = [stress, 1]
pd.concat([df,
pd.concat([df.mul(factor),
df.mul(factor[::-1])]).sort_index()
], ignore_index=True)
AGE POP
0 5.0 100.0
1 10.0 200.0
2 5.5 100.0
3 5.0 110.0
4 11.0 200.0
5 10.0 220.0