Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查列是否以a或b结尾_Python_String_Python 3.x_Pandas_Indexing - Fatal编程技术网

Python 如何检查列是否以a或b结尾

Python 如何检查列是否以a或b结尾,python,string,python-3.x,pandas,indexing,Python,String,Python 3.x,Pandas,Indexing,我需要按最后一个字符过滤列,针对多个字符进行测试 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']) pri

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

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')
在这里,我没有得到所有以
N
H
s
结尾的列

[col for col in df.columns if col[-1] in ['N', 'H', 'S']]
如果我没记错的话,dataframe的
columns
属性不是一个系列,所以不能这样对待它。这是一张单子

要澄清的是,从技术上讲,这些列不是列表。它们是一种特殊类型的熊猫指数的一些变体。但就99%的意图和目的而言,它们可以被视为列表。我想说明的一点是,它们不是系列,因此没有系列方法。

可以使用
元组,然后是布尔索引:

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的内置功能,它允许您提供一个
元组
,以匹配多个项作为替代条件

df_serial = df_copy.filter(regex = '(?:H|N|S)$' , axis=1)
print(df_serial)
使用正则表达式我们可以做到这一点