转换pandas.core.series.Series迄今(年)

发布于 2025-01-21 18:16:06 字数 836 浏览 0 评论 0原文

我正在尝试将系列转换为日期格式。 要转换的专栏是Year,因此我可以每年过滤我的

地区
国家
Daframe分组
/
然后
等等

进行 选项(我将在下面列出),并且它总是返回“系列”类型。我知道这是一个基本问题,但是到目前为止,我尝试过的任何事情都没有奏效,我觉得它就在我面前,我只是看不到它。

选项1:

World['Year']=pd.to_datetime(World['Year'])
type((World['Year']))

Output= pandas.core.series.Series

选项2

World['Year']=pd.to_datetime(World['Year'], format='%Y')
#Didn't work either

选项3

World['Year']=pd.to_datetime(World['Year'], format='%Y').dt.date

我还考虑将其转换为数字,以便我可以过滤数据,但我不确定这是最好的主意。任何建议都非常感谢

I'm trying to convert a Series to a Date Format.
The column I'm trying to convert is Year so I can filter my daframe per year and then group by country, etc.

CountryYear
USA2018
USA2019
CAD2018
ARG2018
ARG2017

I've tried multiple options (which I'll list below) and it always returns a "Series" type. I know this is a basic question but nothing I've tried has worked so far and I feel like it's right in front of me and I'm just not seeing it.

Option 1:

World['Year']=pd.to_datetime(World['Year'])
type((World['Year']))

Output= pandas.core.series.Series

Option 2

World['Year']=pd.to_datetime(World['Year'], format='%Y')
#Didn't work either

Option 3

World['Year']=pd.to_datetime(World['Year'], format='%Y').dt.date

I also thought about converting it to numeric so I can filter the data but I'm not sure that's the best idea. Any suggestions are greatly appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧人 2025-01-28 18:16:06

您不能将系列转换为日期格式,但是您可以做的是将系列的数据类型转换为迄今为止的格式。检查系列使用世界的数据类型['Year']。dtype

You cannot convert Series to Date format but what you can do is convert the datatype of Series to Date format. To check the datatype of a Series use World['Year'].dtype

北城孤痞 2025-01-28 18:16:06

我认为您的意思是如何将其转换为datetime64

基于您的选项2,我们可以使用:=操作员

import pandas as pd
df = pd.DataFrame({
    'Country' : "USA,USA,CAD,ARG,ARG".split(","),
    'Year' : ["2018","2019","2018","2018","2017"]
})
print(df)
df["Year"] = (temp:=pd.to_datetime(df['Year'],format="%Y"))
print(df.dtypes)

以这种方式获得dateTime64 [ns]

I think you mean how to convert it to datetime64

based on your option2, we can use := operator

import pandas as pd
df = pd.DataFrame({
    'Country' : "USA,USA,CAD,ARG,ARG".split(","),
    'Year' : ["2018","2019","2018","2018","2017"]
})
print(df)
df["Year"] = (temp:=pd.to_datetime(df['Year'],format="%Y"))
print(df.dtypes)

this way we can got the datetime64[ns]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文