[英]regex case insensitive filtering of columns in pandas
I am trying to match a string(column) in csv files in python using Python but it does not match anything.我正在尝试使用 Python 在 python 中匹配 csv 文件中的字符串(列),但它不匹配任何内容。 I want the string to be match to be case insensitive.
我希望匹配的字符串不区分大小写。 I am quite new but this is what I tried to do
我很新,但这就是我试图做的
test = pd.read_csv("data.csv")
mytest= pd.DataFrame(test, columns=[re.search("[a-zA-Z1-9_]", "columnname1", re.IGNORECASE),])
print(mytest)
Any help will be highly appreciated任何帮助将不胜感激
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:如果我了解您的意思,您可以
filter
df 以仅返回名称匹配的列并使其不区分大小写:
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
EDIT编辑
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
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 .所以
^
在 str 的开头寻找 'Test' 并且$
标记要搜索的模式的结尾,有一个方便的备忘单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.