在列名中搜索字符串并返回整个列

时间:2021-01-18 08:11:26

标签: python python-3.x pandas dataframe

有没有办法在列名中搜索字符串或子字符串并提取包含该特定字符串的整个列?

我的数据:

enter image description here

我想在数据框中搜索“total”并提取整列(本例中为最后一列)

先谢谢你!

2 个答案:

答案 0 :(得分:1)

如果您要在列名称中明确搜索 Total 之类的关键字,请使用以下内容:

对于这个虚拟数据:

Description,Qty,Unit Cost (AED), Total Cost (AED), Amount (xyz)
string 1, 3, 3000, 9000, 9500
string 1, 3, 3000, 9000, 9500
string 1, 3, 3000, 9000, 9500
string 1, 3, 3000, 9000, 9500
string 1, 3, 3000, 9000, 9500
string 1, 3, 3000, 9000, 9500

试试下面的代码:

import pandas as pd
import re

df = pd.read_csv('test.csv')
print(df)

col = [name for name in df.columns if len(re.findall(r'\b(?:total|amount)\b', name.lower()))!=0]

if len(col)!=0:
    print(df.loc[:, col])

答案 1 :(得分:0)

你可以试试str.contains -

>>> total_mask = df['Description'].str.contains('total|Total')
>>> total_mask
0     True
1    False
2     True
Name: Description, dtype: bool

>>> df.loc[total_mask,:]
          Description  Total Cost (AED)
0  Compensation Total             100.0
2        Total Amount              20.0