how to iterate in pandas dataframe columns

Viewed 46

i need do some operations with my dataframe

my dataframe is

df = pd.DataFrame(data={'col1':[1,2],'col2':[3,4]})

    col1    col2
0      1       3
1      2       4

my operatin is column dependent

for example, i need to add (+) .max() of column to each value in this column

so df.col1.max() is 2 and df.col2.max() is 4

so my output should be:

    col1    col2
0      3       7
1      4       8

i have been try this:

for i in df.columns:
    df.i += df.i.max()

but

AttributeError: 'DataFrame' object has no attribute 'i'
2 Answers

you can chain df.add and df.max and specify the axis which avoids any loops.

df1 = df.add(df.max(axis=0))

print(df1)

  col1  col2
0     3     7
1     4     8

To loop through the columns and add the maximum of each column you can do the following:

for col in df:
    df[col] += df[col].max()

This gives

   col1  col2
0     3     7
1     4     8
Related