[英]Python Extract matching strings from a list
My dataframe has many columns.我的dataframe有很多栏目。 I want to extract columns starting with
9.
Code:我想提取以
9.
开头的列。代码:
df_columns = Index(['_id', 'Time', '2.1', '2.2', '2.3', '2.4', '2.5', '2.6', '2.7', '2.8',
'2.9', '2.10', '2.11', '2.12', '2.13', '2.14', '2.15', '2.16', '2.17',
'2.18', '2.19', '2.20', '9.1', '9.2', '9.3', '9.4', '9.5', '9.6', '9.7',
'9.8', '9.9', '9.10', '9.11', '9.12', '9.13', '9.14', '9.15', '9.16',
'9.17', '9.18', '9.19', '9.20'],
dtype='object')
col9s = df_columns.str.findall(r'\b9.')
Present solution:目前的解决方案:
cols =
Index([ [], [], [], [], [], [], [], [], [],
[], [], [], [], [], [], [], [], [],
[], [], [], [], ['9.'], ['9.'], ['9.'], ['9.'], ['9.'],
['9.'], ['9.'], ['9.'], ['9.'], ['9.'], ['9.'], ['9.'], ['9.'], ['9.'],
['9.'], ['9.'], ['9.'], ['9.'], ['9.'], ['9.']],
dtype='object')
Expected answer:预期答案:
col9s = ['9.1', '9.2', '9.3', '9.4', '9.5', '9.6', '9.7',
'9.8', '9.9', '9.10', '9.11', '9.12', '9.13', '9.14', '9.15', '9.16',
'9.17', '9.18', '9.19', '9.20']
Use filter
with a regex:使用带有正则表达式的
filter
:
col9s = df.filter(regex=r'^9\.').columns
Or, to directly subset the columns:或者,直接对列进行子集化:
df2 = df.filter(regex=r'^9\.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.