10

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'

3 Answers 3

18

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.

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

2 Comments

Thank you!!. It took me hours of useless searches trying to understand how I can work with a PySpark dataframe.
And for hana_ml, you need to convert from a hana_ml.DataFrame to a pandas.DataFrame with .collect(): ``` with dataframe.ConnectionContext(**auth_params) as conn: df = conn.sql(query).collect() ```
11

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

5 Comments

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."
I have pandas .11 and it's not working on mine...you sure it wasn't introduced in .12?
@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).
I mean I installed from macports and macports has the .11 version...that's odd, i'll look into it
@RyanSaxe I wonder if macports has some kind of earlier release candidate for 0.11?
2

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']]

1 Comment

well then maybe macports installs a different version than it says

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.