简体   繁体   中英

Divide several columns by one constant via a for loop

I want to divide several columns by the same constant via a for loop in python. The below is a subset of my dataframe:

dataframe: DF

team   group1   group2   group3   group4
blue   100      400      650      75
green  150      500      350      186
red    200      600      175      540
orange 250      700      900      375

I have attempted:

for col in DF.columns[1:]:
    DF[col] = df[col]/10

the below code works, but I want to use a for loop to iterate through all columns. Ideally, i would not like to have to pick out the numeric columns and apply the division to all columns and if it does run into a string, to ignore the string

DF['group1'] = DF['group1']/10 

the error i am getting is : 'unsupported operand type(s) for /: 'str' and 'int'

这应该工作

df.loc[:, df.columns[1:]] / 10

Before you perform any data analysis or computations, you should determine which series should be numeric. You can check the types of your series via print(df.dtypes) . You can then convert relevant columns to numeric:

df[col_list] = df[col_list].apply(pd.to_numeric, errors='coerce')

Once your series are correctly defined as numeric, you can perform vectorised calculations on them; for example:

df[col_list] /= 10

It's not advisable to keep object series with a mixture of numeric and string data. This will prevent you from performing vectorised calculations, which is a principal benefit of using Pandas in the first place.

You can using select_dtypes with update

df.update(df.select_dtypes(exclude='object').div(10))
df
Out[8]: 
     team  group1  group2  group3  group4
0    blue    10.0    40.0    65.0     7.5
1   green    15.0    50.0    35.0    18.6
2     red    20.0    60.0    17.5    54.0
3  orange    25.0    70.0    90.0    37.5

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