Python Pandas 错误:'DataFrame' 对象没有属性 'loc'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16363233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:23:09  来源:igfitidea点击:

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

pythonpython-2.7numpyscipypandas

提问by Nyxynyx

I am new to pandasand 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 dfworks fine.

我是新手pandas,正在尝试使用 Pandas 0.10.1 版的 Pandas 10 分钟教程。但是,当我执行以下操作时,出现如下所示的错误。print df工作正常。

Why is .locnot working?

为什么.loc不工作?

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'

采纳答案by Andy Hayden

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

loc在 0.11引入的,因此您需要升级您的熊猫以遵循10 分钟的介绍

回答by Ryan Saxe

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

我发现它对我的loc不起作用很奇怪,因为我有 Pandas 0.11,但这里有一些可以满足你想要的东西,只需使用ix

df.ix[:,['A','B']]

回答by fstang

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.

我在处理 pyspark DataFrame 时遇到了这个问题。因此,如果您还使用 pyspark DataFrame,则可以使用 toPandas() 方法将其转换为 Pandas DataFrame。