在python大熊猫中使用loc时出错

灵魂达人

我是python的新手,自己学习熊猫。所以我得到第一种语法的结果,但没有第二种语法的结果。据我了解,我们正在使用loc作为标签。因此,我们应该能够在括号内提及列名。你能帮我吗?

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()
比马莎·哈纳尔(Bimarsha Khanal)

通常,您提到的第一个语法用于访问列。但是,您也可以使用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()方法,因为它返回的数据帧不是序列。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用大熊猫适用

来自分类Dev

大熊猫:使用匿名数据框上的loc过滤行

来自分类Dev

嵌套的联接使用Python大熊猫数据帧

来自分类Dev

将JSON文件装入大熊猫数据框时出错

来自分类Dev

python大熊猫删除字符

来自分类Dev

使用大熊猫的柱子视图吗?

来自分类Dev

使用大熊猫插补

来自分类Dev

如何在大熊猫中使用有条件的聚集体?

来自分类Dev

在大熊猫中使用groupby以获得比例的更有效方法

来自分类Dev

如何在大熊猫中使用硒来阅读网页?

来自分类Dev

在大熊猫中使用周的所有可能值创建 DF

来自分类Dev

大熊猫密谋

来自分类Dev

大熊猫申请

来自分类Dev

大熊猫的选择

来自分类Dev

与大熊猫聚集

来自分类Dev

大熊猫与重复

来自分类Dev

使用多列在大熊猫中转换大熊猫数据框

来自分类Dev

使用逻辑索引时,大熊猫仅应用返回第一个值

来自分类Dev

在大熊猫中绘图:使用子图时没有属性种类吗?

来自分类Dev

大熊猫:df.loc [-1,col]有时可以工作,有时可以用NAN添加额外的行

来自分类Dev

如何使用python检索大熊猫分组依据的最后一列行的值?

来自分类Dev

有领带时,大熊猫如何决定排序?

来自分类Dev

迭代时更新大熊猫中的数据框

来自分类Dev

大熊猫:填写重复日期时填写缺失的日期

来自分类Dev

绘制大熊猫DataFrame时遇到问题

来自分类Dev

大熊猫:加载csv时跳过字符串

来自分类Dev

大熊猫:具有日期的基于标签位置的索引器(loc)的行为

来自分类Dev

Python大熊猫groupby过滤器

来自分类Dev

python - 在应用 %LIKE% 的大熊猫中进行 vlookup