【问题标题】:How to check if a column ends with either a or b in pandas如何检查一列是否以pandas中的a或b结尾
【发布时间】:2019-03-15 15:05:37
【问题描述】:

我需要按最后一个字符过滤列,针对多个字符进行测试。

import numpy as np
import pandas as pd

df = pd.read_table("F:\\bridges.txt", names = ['IDENTIF','RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH', 'LANES', 
 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE']) 

print(df.columns[df.columns.str.endswith('N' or 'H' or 's') ])

输出:

Index(['LOCATION', 'SPAN'], dtype='object')

这里我没有得到所有以NHs 结尾的列。

【问题讨论】:

    标签: python string python-3.x pandas indexing


    【解决方案1】:

    您可以将pd.Index.str.endswithtuple 一起使用,然后是布尔索引:

    L = ['IDENTIF','RIVER', 'LOCATION', 'ERECTED', 'PURPOSE', 'LENGTH',
         'LANES', 'CLEAR-G', 'T-OR-D', 'MATERIAL', 'SPAN', 'REL-L', 'TYPE']
    
    df = pd.DataFrame(columns=L)
    
    cols = df.columns[df.columns.str.endswith(tuple('HNS'))]
    
    Index(['LOCATION', 'LENGTH', 'LANES', 'SPAN'], dtype='object')
    

    该功能模仿 Python 的内置 str.endswith,它允许您提供 tuple 来匹配多个项目作为替代条件。

    【讨论】:

      【解决方案2】:
      [col for col in df.columns if col[-1] in ['N', 'H', 'S']]
      

      如果我没记错的话,数据框的columns 属性不是一个系列,所以你不能这样对待它。这是一个列表。

      为了澄清,这些列在技术上不是列表。它们是一种特殊类型的 pandas 索引的一些变体。但是对于 99% 的意图和目的,它们可以被视为列表。我要澄清的一点是它们是not 系列,因此没有系列方法。

      【讨论】:

        【解决方案3】:
        df_serial = df_copy.filter(regex = '(?:H|N|S)$' , axis=1)
        print(df_serial)
        

        使用正则表达式我们可以做到这一点

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-10-19
          • 2023-02-06
          • 2017-09-04
          • 1970-01-01
          • 1970-01-01
          • 2021-10-26
          • 2014-05-01
          相关资源
          最近更新 更多