簡體   English   中英

在 python pandas 中使用 loc 時出錯

[英]got error while using loc in python pandas

我是 python 的新手,我自己也在學習 pandas。 所以我得到了第一種語法的結果,但沒有得到第二種語法的結果。 據我了解,我們將 loc 用於 label。 因此,我們應該能夠在括號內提及列名。 你能幫幫我嗎?

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

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

錯誤是這樣的:

    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()

通常,您提到的第一個語法用於訪問列。 但是,您也可以使用df.loc[]訪問列。 它可以如下完成。

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

您還可以訪問多個列。 df.loc[:,['shield','max_speed']]但您不能在訪問多個列時使用 value_counts() 方法,因為它返回 dataframe 而不是系列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM