Python-有效访问 pandas 数据框的列 [英] Python - Accessing columns of a Panda Dataframe effectively

查看:67
本文介绍了Python-有效访问 pandas 数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python Pandas上工作了一段时间,现在盯着下面的两个命令,思考两者之间的区别是什么.

I was working with Python Pandas for quite a while and now staring at the two commands below thinking what would be the difference between both.

df1['Col1']          #Shows only the values of 'Col1' from df1 dataframe.
df1[['Col1','Col2']] #Shows the values of both 'Col1' and 'Col2' from df1 dataframe.

我的问题是,当我们能够在单个方括号('[]')的帮助下访问一列时,为什么我们不能为访问多列而做同样的事情.我尝试使用以下命令并遇到错误.

My question is when we are able to access a column with the help of single square brackets ('[ ]'), why can't we do the same for accessing multiple columns. I tried with the below command and encountered error.

df1['Col1','Col2']   #Encountered error

推荐答案

设置

df = pd.DataFrame([[1, 2], [3, 4]], columns=['col1', 'col2'])


在python中,[]__getitem__方法的语法糖.


In python, [] is syntactic sugar for the __getitem__ method.

此:

df['col1']

0    1
1    3
Name: col1, dtype: int64

等效于:

df.__getitem__('col1')

0    1
1    3
Name: col1, dtype: int64

这:

df[['col1', 'col2']]

   col1  col2
0     1     2
1     3     4

与此相同:

df.__getitem__(['col1', 'col2'])

   col1  col2
0     1     2
1     3     4


所以... ,当您执行此操作


So.... when you do this

df['col1', 'col2']

它试图将所有内容强制为单个参数,并且与

It's trying to force whatever is there into a single argument and it's the same as

df.__getitem__(('col1', 'col2'))

哪个会吸引您

KeyError :("col1","col2")

KeyError: ('col1', 'col2')

这篇关于Python-有效访问 pandas 数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆