【问题标题】:Pandas: How to update multiple columns with enumerate loop?Pandas:如何使用枚举循环更新多个列?
【发布时间】:2022-08-09 22:22:27
【问题描述】:
>>> df
name count1 count2 count3 count4
0 a 1 2 10 200
1 b 2 4 20 400
2 c 3 6 30 600
在上面的 df 中,我已经有了名字 count1 和 count2。我想添加列 \'count3\' 和 \'count4\' 分别是 count1 * 10 和 count2 * 10^2。如果可能的话,我想在 count1 和 count2 列上执行此操作,而不是添加新列(类似于 inplace=True)。在我的实际代码中,列数比这多,因此需要使用 for 循环或类似的东西而不是硬编码。谢谢你。
标签:
python
pandas
enumerate
【解决方案1】:
简单的分配应该做:
num_cols = 5 # edit to whatever the real number is
for i in range(1, num_cols + 1):
col_name = 'count' + str(i)
df[col_name] = df[col_name] * (10 ** i) # 10^i
【解决方案2】:
您可以通过重新定义来覆盖列,您可以使用以下方法解决此问题:
df['count3'] = df['count1'] * 10
df['count4'] = df['count2'] * 10 ** 2
我不建议循环,除非逻辑确实重复,如果每列的计算不同,那么循环可能对你没有多大帮助。
【解决方案3】:
您不需要遍历行。
如果您想根据其他列的乘法创建一个新列,这就足够了
>>> df['count3'] = df['count1'] * 10