gpt4 book ai didi

python - 如何从数据框中的字符串中提取年份和月份

转载 作者:行者123 更新时间:2023-12-02 01:27:53 24 4
gpt4 key购买 nike

1。问题

我有一个数据框,年月列包含我要提取的年份和月份。

例如,此列中的元素是“2022-10”。我想从中提取 year=2022month=10

我的当前解决方案是使用applylambda函数:

df['xx_month'] = df['Year-Month'].apply(lambda x: int(x.split('-')[1]))

但是在巨大的数据帧上它非常慢。

如何更有效做到这一点?

2。解决方案

感谢您的智慧,我用代码总结了每个人的解决方案:

df = pd.DataFrame({'Year-Month':['2022-10','2022-11','2022-12']})

df = df.join(
df['Year-Month']
.str.split('-', expand=True)
.set_axis(['year','month'], axis='columns')
)
  • (2) 将数据类型从对象 (str) 转换为日期时间格式 @ Neele22

import pandas as pd
df['Year-Month'] = pd.to_datetime(df['Year-Month'], format="%Y-%m")
  • (3) 使用正则表达式日期时间提取年月@ mozway

df['Year-Month'].str.extract(r'(?P<year>\d+)-(?P<month>\d+)').astype(int)
# If you want to assign the output to the same DataFrame while removing the original Year-Month:
df[['year', 'month']] = df.pop('Year-Month').str.extract(r'(\d+)-(\d+)').astype(int)

或者使用日期时间:

date = pd.to_datetime(df['Year-Month'])

df['year'] = date.dt.year
df['month'] = date.dt.month

3。跟进问题

但是,如果我想在将不完整的“年-月”列从字符串转换为日期时间后用其他日期时间列减去“年-月”,则会出现问题。

例如,如果我想获取每条记录的时间戳之后不晚于2个月的数据。

import dateutil # dateutil is a better package than datetime package according to my experience
df[(df['timestamp'] - df['Year-Month'])>= dateutil.relativedelta.relativedelta(months=0) and (df['timestamp'] - df['Year-Month'])<= datetime.timedelta(months=2)]

此代码在用实际日期时间列减去转换后的“年-月”列时会出现类型错误。

TypeError: Cannot subtract tz-naive and tz-aware datetime-like objects

这两列的类型是:

  • 年月 为 datetime64[ns]
  • 时间戳是datetime64[ns, UTC]

然后,我尝试在将 Year-Month 更改为日期时间类型时指定 utc=True:

df[["Year-Month"]] = pd.to_datetime(df[["Year-Month"]],utc=True,format="%Y-%m")

但是我得到了值错误。

ValueError: to assemble mappings requires at least that [year, month,day] be specified: [day,month,year] is missing

4。带走

  • 如果列中元素的[日、月、年]不完整。 (就像我的例子,我只有年份和月份),我们无法将此列从字符串类型更改为日期时间类型来进行计算。但要使用提取的日期和月份进行计算

  • 如果您像我一样不需要不完整的日期时间列和其他日期时间列之间进行计算,您可以将不完整的日期时间字符串更改为datetime类型,并从中提取[日、月、年]。它比使用正则表达式、拆分和连接更容易

最佳答案

df = pd.DataFrame({'Year-Month':['2022-10','2022-11','2022-12']})

df = df.join(
df['Year-Month']
.str.split('-', expand=True)
.set_axis(['year','month'], axis='columns')
)

关于python - 如何从数据框中的字符串中提取年份和月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74015822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com