简体   繁体   中英

Pandas: How to update multiple columns with enumerate loop?

>>> 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 manually adding df['column3'] is needed. Thank you.

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

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.

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

Let's try

cols = ['count1', 'count2']
outs = ['count3', 'count4']

df = df.join(pd.concat([df[col].mul(10 ** (i+1)).to_frame(outs[i])
                        for i, col in enumerate(cols)], axis=1))
print(df)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM