Pandas error: 'DataFrame' object has no attribute 'loc'

40,053

Solution 1

loc was introduced in 0.11, so you'll need to upgrade your pandas to follow the 10minute introduction.

Solution 2

I came across this question when I was dealing with pyspark DataFrame. So, if you're also using pyspark DataFrame, you can convert it to pandas DataFrame using toPandas() method.

Solution 3

I am finding it odd that loc isn't working on mine because I have pandas 0.11, but here is something that will work for what you want, just use ix

df.ix[:,['A','B']]
Share:
40,053
Nyxynyx
Author by

Nyxynyx

Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS

Updated on July 19, 2022

Comments

  • Nyxynyx
    Nyxynyx almost 2 years

    I am new to pandas and is trying the Pandas 10 minute tutorial with pandas version 0.10.1. However when I do the following, I get the error as shown below. print df works fine.

    Why is .loc not working?

    Code

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(np.random.randn(6,4), index=pd.date_range('20130101', periods=6), columns=['A','B','C','D'])
    df.loc[:,['A', 'B']]
    

    Error:

    AttributeError                            Traceback (most recent call last)
    <ipython-input-4-8513cb2c6dc7> in <module>()
    ----> 1 df.loc[:,['A', 'B']]
    
    C:\Python27\lib\site-packages\pandas\core\frame.pyc in __getattr__(self, name)
       2044             return self[name]
       2045         raise AttributeError("'%s' object has no attribute '%s'" %
    -> 2046                              (type(self).__name__, name))
       2047 
       2048     def __setattr__(self, name, value):
    
    AttributeError: 'DataFrame' object has no attribute 'loc'
    
  • DSM
    DSM about 11 years
    In fact, at this moment, it's the first new feature advertised on the front page: "New precision indexing fields loc, iloc, at, and iat, to reduce occasional ambiguity in the catch-all hitherto ix method."
  • Ryan Saxe
    Ryan Saxe about 11 years
    I have pandas .11 and it's not working on mine...you sure it wasn't introduced in .12?
  • Andy Hayden
    Andy Hayden about 11 years
    @RyanSaxe in the what's new page it states "starting in 0.11..." The OPs code works fine for me in 0.11 (and 0.12dev).
  • Ryan Saxe
    Ryan Saxe about 11 years
    I mean I installed from macports and macports has the .11 version...that's odd, i'll look into it
  • Andy Hayden
    Andy Hayden about 11 years
    @RyanSaxe I wonder if macports has some kind of earlier release candidate for 0.11?
  • Ryan Saxe
    Ryan Saxe about 11 years
    well then maybe macports installs a different version than it says
  • Freddy
    Freddy about 4 years
    Thank you!!. It took me hours of useless searches trying to understand how I can work with a PySpark dataframe.