更新时间:2023-02-04 17:27:10
如果我了解您的要求,则可以filter
将df仅返回名称匹配的列并使其不区分大小写:>
If I understand what you're after you can filter
your df to only return the columns where the name matches and make it case-insensitive:
In [298]:
df = pd.DataFrame({'columnname1':np.arange(5), 'ColumnName1':np.arange(5), 'columnname2':0, 'column name 1':0})
df
Out[298]:
ColumnName1 column name 1 columnname1 columnname2
0 0 0 0 0
1 1 0 1 0
2 2 0 2 0
3 3 0 3 0
4 4 0 4 0
In [299]:
import re
df.filter(regex=re.compile("columnname1", re.IGNORECASE))
Out[299]:
ColumnName1 columnname1
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
编辑
仅匹配名称但不带单词,因此匹配测试"而不匹配我的测试":
For matching just the name without words preceding it, so matching on 'Test' but not 'My Test':
In [52]:
df = pd.DataFrame({'Test':np.arange(5), 'ColumnName1':np.arange(5), 'My Test':0, 'My column name 1':0})
import re
df.filter(regex=re.compile(r"^Test$", re.IGNORECASE))
Out[52]:
Test
0 0
1 1
2 2
3 3
4 4
因此^
在str的开头查找'Test',而$
标志着要搜索的模式的结尾,这里有一个方便的
So the ^
looks for 'Test' at the beginning of the str and the $
marks the end of the pattern to search, there is a handy cheat sheet.