Home > Software design >  Pandas: How to update multiple columns with enumerate loop?
Pandas: How to update multiple columns with enumerate loop?

Time:08-09

>>> df
  name  count1 count2 count3 count4
0    a      1     2     10     200
1    b      2     4     20     400
2    c      3     6     30     600

In the above df, I have the name, count1, and count2 already. I'd like to add columns 'count3' and 'count4' which are count1 * 10 and count2 * 10^2, respectively. If possible, I'd like to do this over the count1 and count2 columns rather than adding new columns (similar to inplace=True). In my actual code, there are more columns than this so using a for loop or something similar instead of hardcoding is needed. Thank you.

CodePudding user response:

You can create the respective column name and the correct number to multiply in a loop like so:

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

CodePudding user response:

You can overwrite a column by re-defining it, you can solve this by using:

df['count3'] = df['count1'] * 10
df['count4'] = df['count2'] * 10 ** 2

I wouldn't suggest looping unless logics do repeat, if it's a different calculation per column, then looping might not help you much.

CodePudding user response:

You do not need to iterate over rows. If you want to create a new column based on multiplication from other this would be enough

>>> df['count3'] = df['count1'] * 10
  • Related