Answers:
只需遍历DataFrame.columns
,这是一个示例,在此示例中,您将获得匹配的列名称列表:
import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)
输出:
['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']
说明:
df.columns
返回列名列表[col for col in df.columns if 'spike' in col]
df.columns
使用变量遍历列表col
并将其添加到结果列表(如果col
包含)'spike'
。此语法是列表理解。如果只希望结果数据集的列匹配,则可以执行以下操作:
df2 = df.filter(regex='spike')
print(df2)
输出:
spike-2 spiked-in
0 1 7
1 2 8
2 3 9
DataFrame.filter
FYI的功能(如果需要,您可以提供正则表达式)
df[df.columns.drop(spike_cols)]
,您会得到一个DataFrame
列表中没有这些列的列表spike_cols
,而使用不希望的正则表达式可以获取这些列。
df[[col for col in df.columns if "spike" in col]]
您也可以使用 df.columns[df.columns.str.contains(pat = 'spike')]
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
colNames = df.columns[df.columns.str.contains(pat = 'spike')]
print(colNames)
这将输出列名称: 'spike-2', 'spiked-in'
有关pandas.Series.str.contains的更多信息。
# select columns containing 'spike'
df.filter(like='spike', axis=1)
您还可以按名称选择正则表达式。请参阅:pandas.DataFrame.filter
df.loc[:,df.columns.str.contains("spike")]
根据“开始”,“包含”和“结束”获取名称和子集:
# from: /programming/21285380/find-column-whose-name-contains-a-specific-string
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.contains.html
# from: https://cmdlinetips.com/2019/04/how-to-select-columns-using-prefix-suffix-of-column-names-in-pandas/
# from: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html
import pandas as pd
data = {'spike_starts': [1,2,3], 'ends_spike_starts': [4,5,6], 'ends_spike': [7,8,9], 'not': [10,11,12]}
df = pd.DataFrame(data)
print("\n")
print("----------------------------------------")
colNames_contains = df.columns[df.columns.str.contains(pat = 'spike')].tolist()
print("Contains")
print(colNames_contains)
print("\n")
print("----------------------------------------")
colNames_starts = df.columns[df.columns.str.contains(pat = '^spike')].tolist()
print("Starts")
print(colNames_starts)
print("\n")
print("----------------------------------------")
colNames_ends = df.columns[df.columns.str.contains(pat = 'spike$')].tolist()
print("Ends")
print(colNames_ends)
print("\n")
print("----------------------------------------")
df_subset_start = df.filter(regex='^spike',axis=1)
print("Starts")
print(df_subset_start)
print("\n")
print("----------------------------------------")
df_subset_contains = df.filter(regex='spike',axis=1)
print("Contains")
print(df_subset_contains)
print("\n")
print("----------------------------------------")
df_subset_ends = df.filter(regex='spike$',axis=1)
print("Ends")
print(df_subset_ends)