【问题标题】:DataFrame cannot be sliced direfctly using [] operator as SeriesDataFrame 不能直接使用 [] 运算符作为 Series 进行切片
【发布时间】:2016-08-02 10:16:04
【问题描述】:

这是我刚刚意识到的,希望对像我这样的pandas初学者有用-为什么最后一行会出错?因为当从一个DataFrame中选择一列时,它就变成了一个Series,可以直接用简洁的语法为[]进行索引。但是,当您从 DataFrame 中选择列列表时,它仍会返回一个无法直接使用 [] 切片的 DataFrame。

In[178]: df
Out[177]: 
    name  age sex        job
0   John   15   M    Student
1   Mike   30   M      Labor
2   Lily   41   F    Student
3   Dave   66   M      Labor
4    Sam   23   F  Scientist
5   Luke    7   M      Labor
6  Ellen   80   F      Labor
7  Jacob   52   M      Actor
In[179]: df.set_index('name', inplace=True, drop=True)
In[180]: df
Out[179]: 
       age sex        job
name                     
John    15   M    Student
Mike    30   M      Labor
Lily    41   F    Student
Dave    66   M      Labor
Sam     23   F  Scientist
Luke     7   M      Labor
Ellen   80   F      Labor
Jacob   52   M      Actor
In[181]: df['age']['John']
Out[180]: 15
In[182]: type(df['age'])
Out[181]: pandas.core.series.Series
In[183]: type(df[['age']])
Out[182]: pandas.core.frame.DataFrame
In[184]: df[['age']]['John'] # This is Wrong

【问题讨论】:

  • 我只是想让它更易于阅读。但是我找不到如何将整个背景和前景颜色从 IDE(在这种情况下为 PyCharm)粘贴到 StackOverflow,就像许多 Python 程序员习惯的那样——它在 Outlook 电子邮件中完美运行。请教我。我阅读了帮助,我只找到基本的 HTML 支持。我找不到特定语言的突出显示支持,抱歉。
  • 好的,谢谢。我要编辑我所有的帖子。相信我,当我决定发布图片时,我的意图是最好的。实际上,截屏,保存图片然后上传到那里,比在代码文本上按 Ctrl+K 更难。

标签: python-3.x pandas dataframe series


【解决方案1】:

要使最后一行工作,您需要以这种方式使用df[['age']]['age'][df['name'] =='John']。这显然是不好的风格。您的最后一行代码不起作用的原因是 df[['age']] 返回一个数据框,其中包含名为 'age' 的单列,索引从 0 到 7。

In [4]: df[['age']]
Out[4]:
   age
0   15
1   30
2   41
3   66
4   23
5    7
6   80
7   52

当您尝试使用 'John' 对数据框进行切片时,Pandas 会检查数据框并且找不到任何名为 John 的列。您可以执行以下操作来查找约翰的年龄

In [15]: df[['age']]['age'][df['name'] =='John']
Out[15]:
0    15
Name: age, dtype: int64

# get the exact value
In [16]: df[['age']]['age'][df['name'] =='John'][0]
Out[16]:
15

# or simply
In [18]: df[df['name'] =='John']['age'][0]
Out[18]: 15

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2020-01-11
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多