Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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 是否有区分大小写的方法按标题筛选数据帧中的列?_Python_Pandas - Fatal编程技术网

Python 是否有区分大小写的方法按标题筛选数据帧中的列?

Python 是否有区分大小写的方法按标题筛选数据帧中的列?,python,pandas,Python,Pandas,我有一个具有多列和不同标题的数据框架。 我想过滤数据框,只保留以字母I开头的列。我的一些列标题有字母I,但以不同的字母开头 有办法做到这一点吗? 我尝试使用df.filter,但由于某些原因,它不区分大小写。您可以将df.filter与regex参数一起使用: df.filter(regex=r'(?i)^i') 这将返回以I开头的列,忽略大小写。 示例如下: 让我们考虑输入数据框: df = pd.DataFrame(np.random.randint(0,20,(5,4)),

我有一个具有多列和不同标题的数据框架。 我想过滤数据框,只保留以字母I开头的列。我的一些列标题有字母I,但以不同的字母开头

有办法做到这一点吗?
我尝试使用df.filter,但由于某些原因,它不区分大小写。

您可以将
df.filter
regex
参数一起使用:

df.filter(regex=r'(?i)^i')
这将返回以
I
开头的列,忽略大小写。

示例如下:

让我们考虑输入数据框:

df = pd.DataFrame(np.random.randint(0,20,(5,4)),
      columns=['itest','Itest','another','anothericol'])


使用
df.filter

print(df.filter(regex=r'(?i)^i'))

   itest  Itest
0      1      4
1     17     10
2     16     18
3     10     12
4      6     15

您可以详细地将列表理解传递给
loc
df.loc[:,[col.startswith(“I”)表示df中的col]
。对于那些不是雷格克斯勇士的人来说可能很方便。此外,我可能错了,但OP似乎想要一些区分大小写的东西,并且只过滤大写字母
I
@sammywemmy one可以转换为小写字母,并将startswith与小写字母“I”一起使用。然而,这似乎已经得到了回答,因此我将编辑这是一个社区维基。另外,我认为我们可以使用df.columns.str.startswith(('I','I'))作为str.startswith获取一个元组,并传递到loc.yea。对。元组部分也是一个很好的部分。
print(df.filter(regex=r'(?i)^i'))

   itest  Itest
0      1      4
1     17     10
2     16     18
3     10     12
4      6     15