0

I am passing a column called petrol['tax'] of a dataframe to a function using .apply which returns 1st quartile. I am trying to use the below code but it throws me this error 'float' object has no attribute 'quantile'.

def Quartile(petrol_attrib):
    return petrol_attrib.quantile(.25)

petrol['tax'].apply(Quartile)

I need help to implement this.

2
  • Oops that was quantile. There is qcut Commented Sep 24, 2018 at 14:37
  • I need to know if petrol['tax'].quartile(.25) is possible and why cant this is not possible petrol_attrib.quantile(.25) ? Because the same petrol['tax'] column only i am passing as argument. Commented Sep 24, 2018 at 14:39

3 Answers 3

1
 df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]),
                  columns=['a', 'b'])

Now you can use the quantile function in pandas. Make sure you using the numbers between 0 and 1. Here an example below:

 df.a.quantile(0.5)
 3.25

You can apply the function to the whole dataframe 
Sign up to request clarification or add additional context in comments.

Comments

0

The apply function serializes the object that is passed to it and performs the function on each element individually. You can call quantile() on a DataFrame or a Series (unlike some other answers have stated) but you can't call it on a float. You are effectively trying to call quantile() on every element of the Series, since each element in the series is a float and .quantile() doesn't work on floats, that's why you are getting an error.

I recommend simply calling petrol['tax'].quantile(.25) directly. However, if you prefer to keep your custom function, just pass the Series to it directly rather than using .apply(): Quartile(petrol['tax'])

Comments

0

You can use the quartile function on a data frame, not series. You can use the same method by writing petrol[['tax']] instead of petrol['tax']. The version below is the modified one:

def Quartile(petrol_attrib):
    return petrol_attrib.quantile(.25)

petrol[['tax']].apply(Quartile)

1 Comment

Please format any code in your answer posts using the appropriate tags.

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.