【问题标题】:Pandas column access w/column names containing spacesPandas 列访问,列名包含空格
【发布时间】:2012-11-25 06:39:27
【问题描述】:

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

from pandas import DataFrame

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

df1.data1

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

from pandas import DataFrame

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

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

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

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

得到是另一种方式。我疯狂地用谷歌搜索它,想不出任何其他方法来搜索它。我已经阅读了 SO 上包含“column”、“string”和“pandas”的所有 96 个条目,但找不到以前的答案。这是唯一的方法,还是有更好的方法?

【问题讨论】:

    标签: python pandas string dataframe


    【解决方案1】:

    旧帖子,但可能很有趣:一个想法(这是破坏性的,但如果你想要它快速而肮脏的话就可以完成工作)是使用下划线重命名列:

    df1.columns = [c.replace(' ', '_') for c in df1.columns]
    

    【讨论】:

    • 如果您也想将列标准化为小写,请使用df1.columns = [c.lower().replace(' ', '_') for c in df1.columns]
    • 读取和清理数据帧的好方法是使用方法链。您可以使用rename 方法,而不是使用列表解析来设置columns 属性:df1 = pandas.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'dat a1': range(7)}).rename(lambda x: x.replace(' ', '_'), axis=1)
    • 另一种方法是使用strip() 函数:df1.columns = [c.strip() for c in df1.columns]
    【解决方案2】:

    我认为默认方式是使用括号方法而不是点符号。

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

    其他方法,例如将其作为属性公开,更多的是为了方便。

    【讨论】:

    • 谢谢,你不应该像以前那样难倒我。
    • 感谢您的评论。我通常使用点来访问我的列(df.col_name),但只知道这个技巧可以通过使用 df[column name with space"] 来访问带有空格的列名。谢谢。
    【解决方案3】:

    如果您想为 pandas 方法(如 assign)提供间隔列名称,您可以对输入进行字典化。

    df.assign(**{'space column': (lambda x: x['space column2'])})
    

    【讨论】:

      【解决方案4】:

      虽然在使用字典或 []-selection 时接受的答案适用于列规范,但它并不能推广到需要引用列的其他情况,例如 assign 方法:

      > df.assign("data 2" = lambda x: x.sum(axis=1)
      SyntaxError: keyword can't be an expression
      

      【讨论】:

      • 是的,我希望有一个解决方案,因为据我所知,assign 没有可链接的替代方案。我想这应该是一个单独的 SO 问题。
      • 答案是将字典作为关键字参数传递。 df.assign(**{"data 2": lambda x: x.sum(axis=1)})
      【解决方案5】:

      如果您想应用过滤,也可以使用包含空格的列名,例如过滤 NULL 值或空字符串:

      df_package[(df_package['Country_Region Code'].notnull()) | 
      (df_package['Country_Region Code'] != u'')]
      

      感谢Rutger Kassiesanswer

      【讨论】:

        【解决方案6】:

        你可以用df['Column Name']做到这一点

        【讨论】:

          猜你喜欢
          • 2019-03-17
          • 1970-01-01
          • 2021-01-17
          • 1970-01-01
          • 2017-08-15
          • 1970-01-01
          • 2017-11-30
          • 2019-01-26
          • 1970-01-01
          相关资源
          最近更新 更多