通过列名包含空格的 pandas 列访问 [英] Pandas column access w/column names containing spaces

查看:82
本文介绍了通过列名包含空格的 pandas 列访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我导入或创建一个不包含空格的熊猫列,则可以这样访问它:

If I import or create a pandas column that contains no spaces, I can access it as such:

df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
                 'data1': range(7)})

df1.data1

它将为我返回该系列.但是,如果该列的名称中有空格,则无法通过该方法进行访问:

which would return that series for me. If, however, that column has a space in its name, it isn't accessible via that method:

df2 = DataFrame({'key': ['a','b','d'],
                 'data 2': range(3)})

df2.data 2      # <--- not the droid i'm looking for.

我知道我可以使用.xs()进行访问:

I know I can access it using .xs():

df2.xs('data 2', axis=1)

还有 got 是另一种方式.我已经疯狂地搜索过它,想不出其他任何方法来搜索它.我在这里已经阅读了所有包含"column","string"和"pandas"的96个条目,并且找不到以前的答案.这是唯一的方法,还是有更好的方法?

There's got to be another way. I've googled it like mad and can't think of any other way to google it. I've read all 96 entries here on SO that contain "column" and "string" and "pandas" and could find no previous answer. Is this the only way, or is there something better?

谢谢!

推荐答案

我认为 的默认方法是使用:

I think the default way is to use:

df1 = pandas.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
             'dat a1': range(7)})

df1['dat a1']

为方便起见,其他方法(例如将其作为属性公开)更多.

The other methods, like exposing it as an attribute are more for convenience.

这篇关于通过列名包含空格的 pandas 列访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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