11

I'm a newbie to pandas dataframe, and I wanted to apply a function to each column so that it computes for each element x, x/max of column.

I referenced this question, but am having trouble accessing the maximum of each column. Thanks in advance Pandas DataFrame: apply function to all columns

Input:

      A  B  C  D
   0  8  3  5  8
   1  9  4  0  4
   2  5  4  3  8
   3  4  8  5  1

Output:

      A     B     C    D
   0  8/9  3/8  5/5  8/8
   1  9/9  4/8  0/5  4/8
   2  5/9  4/8  3/5  8/8
   3  4/9  8/8  5/5  1/8
2
  • Would "0.888.." suffice, or do you really need the fraction 8/9? Commented Dec 18, 2012 at 17:59
  • Oh yes, 0.888 would be great. It was intended to show the operation. Sorry for the confusion. Commented Dec 18, 2012 at 18:02

1 Answer 1

14

Something like this should work:

>>> from pandas import DataFrame
>>> 
>>> df = DataFrame({"A": [8,9,5,4], "B": [3,4,4,8], "C": [5,0,3,5], "D": [8,4,8,1]})
>>> df.max()
A    9
B    8
C    5
D    8
>>> (df * 1.0)/df.max()
          A      B    C      D
0  0.888889  0.375  1.0  1.000
1  1.000000  0.500  0.0  0.500
2  0.555556  0.500  0.6  1.000
3  0.444444  1.000  1.0  0.125

Note that I multiplied df by 1.0 so that it didn't consists of ints anymore (.astype(float) would have worked too) to avoid integer division and a resulting DataFrame full of 0s and 1s.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.