Select 名称遵循 pandas 中给定模式的 DataFrame 列
Select DataFrame columns with names that follow a given pattern in pandas
我正在使用包含大量列的 DataFrame
。我希望能够 select 遵循给定模式的列子集。
例子
df = pd.DataFrame({'a_1': [1,2,3],'b': [2,3,4],'c_1': [3,4,5]})
a_1 b c_1
0 1 2 3
1 2 3 4
2 3 4 5
我希望能够 select 仅以 _1
结尾的列(这可以使用正则表达式语法表示为 '.*_1'
)导致:
a_1 c_1
0 1 3
1 2 4
2 3 5
将 boolean indexing
with mask by endswith
or contains
与正则表达式一起使用:
df1 = df.loc[:, df.columns.str.endswith('_1')]
df1 = df.loc[:, df.columns.str.contains('_1$')]
df1 = df.loc[:, df.columns.str.contains('.*_1')]
print (df1)
a_1 c_1
0 1 3
1 2 4
2 3 5
您可以对以 _1
:
结尾的 select 列使用列表理解
df = pd.DataFrame({'a_1': [1,2,3], 'b': [2,3,4], 'c_1': [3,4,5]})
filter_col = [col for col in df if col.endswith('_1')]
df[filter_col]
a_1 c_1
0 1 3
1 2 4
2 3 5
有一个特殊的方法 - DataFrame.filter():
In [178]: df.filter(regex=r'_1$')
Out[178]:
a_1 c_1
0 1 3
1 2 4
2 3 5
我正在使用包含大量列的 DataFrame
。我希望能够 select 遵循给定模式的列子集。
例子
df = pd.DataFrame({'a_1': [1,2,3],'b': [2,3,4],'c_1': [3,4,5]})
a_1 b c_1
0 1 2 3
1 2 3 4
2 3 4 5
我希望能够 select 仅以 _1
结尾的列(这可以使用正则表达式语法表示为 '.*_1'
)导致:
a_1 c_1
0 1 3
1 2 4
2 3 5
将 boolean indexing
with mask by endswith
or contains
与正则表达式一起使用:
df1 = df.loc[:, df.columns.str.endswith('_1')]
df1 = df.loc[:, df.columns.str.contains('_1$')]
df1 = df.loc[:, df.columns.str.contains('.*_1')]
print (df1)
a_1 c_1
0 1 3
1 2 4
2 3 5
您可以对以 _1
:
df = pd.DataFrame({'a_1': [1,2,3], 'b': [2,3,4], 'c_1': [3,4,5]})
filter_col = [col for col in df if col.endswith('_1')]
df[filter_col]
a_1 c_1
0 1 3
1 2 4
2 3 5
有一个特殊的方法 - DataFrame.filter():
In [178]: df.filter(regex=r'_1$')
Out[178]:
a_1 c_1
0 1 3
1 2 4
2 3 5