首页 > 解决方案 > 如何搜索列列表以找到特定的正则表达式模式,并根据该值创建新列?

问题描述

我在一组 CSV 文件中有一个列列表,我正在搜索并分配新的列名。

我想搜索列列表以查找名称中包含日期变量 (YYYY-MM-DD) 的情况(我不知道日期是什么,甚至不知道它是否存在)。我确实知道很可能会有一个col_of_interest_variable我绝对想排除的变量。

然后我想搜索包含列的日期列表,然后选择最新的一个。我有部分功能,但不确定搜索列列表并创建一个包含与此公式匹配的所有列的新列表的最佳方法:

哦,这个功能的问题是我正在阅读数百个 CSV 文件,这些文件都包含不同#s 的不同名称的列。我知道的一件事是下面的模式,包含最近的日期,是我想要的列。

col_of_interest_\d{4}-\d{2}-\d{2}_variable

这是我目前拥有的,但它并没有按我想要的方式工作: findall 方法似乎不是最好的方法,并且获取 date_cols 的列表理解没有获得最近的日期。

    filtered_columns = [
        re.findall("col_of_interest_\d{4}-\d{2}-\d{2}_variable", column)
        for column in df.columns
    ]
    if len(filtered_columns) == 0:
        df["new_col_of_interest"] = np.nan

    if len(filtered_columns) == 1:
        df["new_col_of_interest"] = df[col_of_interest_\d{4}-\d{2}-\d{2}_variable]

    elif len(filtered_columns) > 1:
        date_cols = next(s for s in filtered_columns if s)

        application_dates = [
            pd.to_datetime(re.search("\d{4}-\d{2}-\d{2}", column).group())
            for column in date_cols
        ]
        last_application_date_index = np.argmax(application_dates)

        df["new_col_of_interest"] = df[
            filtered_columns[last_application_date_index]
        ]

在此处输入图像描述

我的目标是让这个 Dataframe 输出,其中包含一个新列,new_col_of_interest其中包含列中的值(在这种情况下)new_col_of_interest_2020-08-28_variable

标签: pythonregexpandas

解决方案


如果您确定您编写的正则表达式仅返回一个匹配项或根本不返回匹配项,并且至少一个列名将具有您想要的日期,那么您可以尝试以下方法。

import re
from datetime import datetime

for idx, col in enumerate(df.columns):
    matches = re.findall('col_of_interest_\d{4}-\d{2}-\d{2}_variable', col)
    if matches:
        match = matches[0]
        date = match.split('_')[-2]
        date = datetime.strptime(date, '%Y-%d-%m')
        if idx == 0 or date>latest_date:
            latest_date = date
            latest_match = match
df['new_col_of_interest'] = df[latest_match]

如果需要,您可以更改日期的格式strptime()


推荐阅读