按Pandas中的列内容标记日期(矢量化)

2024-06-16 14:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下表格的数据:

     JournalInformation                      Month
Dec. American Journal of Science
Molecular Methods. Aug DOI: 10101
Science Journal Jun.
Dec. Cognitive Science weekly

目标:

     JournalInformation                      Month
Dec. American Journal of Science               12
Molecular Methods. Aug DOI: 10101               8
Science Journal Jun.                           6
Dec. Cognitive Science weekly                  12

我有数百万行,所以解决方案需要很快。你知道吗

我发现df.JournalInformation.apply(set("Dec").issubset) 是一种很快得到布尔值列表的方法…但是, 因为pandas似乎对任何类型的多索引赋值都不满意,所以我不清楚如何操作布尔信息(除了创建12列…这很难看)。你知道吗


月数:

months_of_year = {  "Jan" : 1
                  , "Feb" : 2
                  , "Mar" : 3
                  , "Apr" : 4
                  , "May" : 5
                  , "Jun" : 6
                  , "Jul" : 7
                  , "Aug" : 8
                  , "Sept": 9
                  , "Oct" : 10
                  , "Nov" : 11
                  , "Dec" : 12
}

Tags: ofdoijunaugdeccognitive表格methods
1条回答
网友
1楼 · 发布于 2024-06-16 14:15:35

使用str.extractmap

regex = r'({})'.format('|'.join(months_of_year.keys()))
df.JournalInformation.str.extract(regex, expand=False).map(months_of_year)

说明

print regex

(Feb|Aug|Jan|Dec|Sept|Oct|Mar|May|Jun|Jul|Apr|Nov)

regexextract中使用时,它将拉出与months字典中的键匹配的第一个子字符串。然后map将从字典中获取匹配值。你知道吗

相关问题 更多 >