首页 > 解决方案 > 提取字符串列中遇到的第一个月名称

问题描述

给定一列summary

summary
'Altemio C. Sanchez (born January 19, 1958) is a Puerto Rican serial killer'
'Alton Coleman (November 6, 1955 - April 26, 2002) was an American serial killer'
'Amelia Elizabeth Dyer (born Hobley; 1836 - 10 June 1896) was one of the most prolific serial killers'
'Amy Duggan "Sister" Archer-Gilligan (31 October 1873 - April 23, 1962) was a serial killer' 

我正在尝试提取该人的出生月份,如果他们没有出生月份也没关系,但如果他们有,则需要提取。

现在,如果找到模式,我正在使用 numpy.where() 填充新列。

killers['month'] =  np.where(killers['summary'].astype(str).str.lower().str.contains('january'),'01',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('february'),'02',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('march'),'03',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('april'),'04',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('may'),'05',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('june'),'06',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('july'),'07',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('august'),'08',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('september'),'09',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('october'),'10',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('november'),'11',
                    np.where(killers['summary'].astype(str).str.lower().str.contains('december'),'12', ''))))))))))))

但是某些死亡月份(即 10 月出生,4 月死亡)会覆盖month列中的出生月份

有没有办法专门保留第一个找到的月份?

标签: pythonpandas

解决方案


您可以使用map(见评论):

# Define a month mapper (name to number)
month_map = dict(zip(
    ['january','february', 'march', 'april', 'may', 'june', 'july',
     'august', 'september', 'october', 'november', 'december'],
    range(1,13)
))

# Extracting the first month name and map them to the correspondent number
killers['month'] = (df.summary.str.lower() # set strings to lower
 .str.findall('|'.join(month_map.keys())) # extract all available months
 .map(lambda x: x[0]) # Extract just the first one
 .map(month_map) # map them to its number
)

注意:这仅在每个字符串至少有一个月可用的情况下才有效,否则它将引发IndexError. 您可以通过将第一map行更改为:

.map(lambda x: x[0] if len(x)>0 else np.nan)

NaN没有几个月的时间你就可以得到字符串。


推荐阅读