简体   繁体   English

在 python pandas 中使用 loc 时出错

[英]got error while using loc in python pandas

I am new to python and learning pandas myself.我是 python 的新手,我自己也在学习 pandas。 So I get the result for the first syntax but not for the second syntax.所以我得到了第一种语法的结果,但没有得到第二种语法的结果。 As per my understanding, we are using loc for label.据我了解,我们将 loc 用于 label。 So, we should be able to mention the column name inside the parenthesis.因此,我们应该能够在括号内提及列名。 Could you please help me out?你能帮帮我吗?

df1['EdLevel'].value_counts()--this gives the results

df1.loc['EdLevel'].value_counts()---gives error while running.

The error is something like this:错误是这样的:

    KeyError                                  Traceback (most recent call last)
    ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       2645             try:
    -> 2646                 return self._engine.get_loc(key)
       2647             except KeyError:
    
    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
    
    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
    
    pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
    
    KeyError: 'EdLevel'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-105-bc8968bf3244> in <module>
----> 1 df1.loc['EdLevel'].value_counts()

Generally, The first syntax you mentioned is used to acess column.通常,您提到的第一个语法用于访问列。 But, you can also acess column using df.loc[] also.但是,您也可以使用df.loc[]访问列。 It can be done as below.它可以如下完成。

import pandas as pd
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
      index=['cobra', 'viper', 'sidewinder'],
      columns=['max_speed', 'shield'])
        max_speed shield
cobra       1       2
viper       4       5
sidewinder  7       8
df.loc[:,'shield'] # acess entire 'shield' column

cobra         2
viper         5
sidewinder    8
Name: shield, dtype: int64

You can also acess multiple columns.您还可以访问多个列。 df.loc[:,['shield','max_speed']] but you cannot use value_counts() method while acessing multiple columns as it returns dataframe not series. df.loc[:,['shield','max_speed']]但您不能在访问多个列时使用 value_counts() 方法,因为它返回 dataframe 而不是系列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM