python - 如何搜索列列表以找到特定的正则表达式模式,并根据该值创建新列?
问题描述
我在一组 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
。
解决方案
如果您确定您编写的正则表达式仅返回一个匹配项或根本不返回匹配项,并且至少一个列名将具有您想要的日期,那么您可以尝试以下方法。
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()
。
推荐阅读
- javascript - 如何在 Three.js 中制作一个有效的天空盒?
- c++ - 使用可变参数模板化帮助器的多个 std::variant 访问
- assembly - 阵列平均 MIPS
- python - 你如何以 JSON 格式编写 Python 日期时间?
- autohotkey - 我是否错误地引用了 hwnd?无法使用 AutoHotkey 从简单的记事本窗口中获取文本
- plot - 如何解决在 scilab 中绘制极坐标图的错误
- python - VS Code 数据科学变量浏览器和查看器选项
- ios - 使用 Apple 登录时出现“Invalid_client”错误
- android-studio - Flutter:在 IOS 模拟器上运行应用程序抛出 Podfile 错误
- serialization - Newtonsoft.json JsonConvert.SerializeObject - 仅序列化第一级 - MaxDepth 不适用于序列化