pandas 在Python中存储没有年份的日和月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41798301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:50:49  来源:igfitidea点击:

Storing day and month without year in Python

pythonpython-2.7datetimepandas

提问by a-joyce

I simply need to store a month and a date (a birthday) WITHOUT a year value.

我只需要存储没有年份值的月份和日期(生日)。

When looking at the documentation for pandas (mostly because it has useful time manipulation features), specifically Periods, it states that you need to pass in a timespan and a frequency. I'm not quite sure how to use the frequency part regarding to my problem. What frequency would be most appropriate? Is using pd even the best way to do this?

在查看 pandas 的文档时(主要是因为它具有有用的时间操作功能),特别是 Periods,它指出您需要传入时间跨度和频率。我不太确定如何使用频率部分来解决我的问题。什么频率最合适?使用 pd 甚至是最好的方法吗?

Thanks!

谢谢!

回答by piRSquared

That isn't how Period's work. They represent a specific period in time. Similar to how Timestamp's represent specific points in time.

这不是Period工作的方式。它们代表特定的时间段。类似于如何Timestamp代表特定的时间点。

You seem to want a generic Month-Daylabel. You can use strftimeto get the string but you'll lose any date manipulation.

您似乎想要一个通用Month-Day标签。您可以使用strftime获取字符串,但您将丢失任何日期操作。

Consider the series of timestamps with timestamp indices.

考虑带有时间戳索引的一系列时间戳。

s = pd.date_range('2011-01-31', periods=12, freq='M').to_series()
s

2011-01-31   2011-01-31
2011-02-28   2011-02-28
2011-03-31   2011-03-31
2011-04-30   2011-04-30
2011-05-31   2011-05-31
2011-06-30   2011-06-30
2011-07-31   2011-07-31
2011-08-31   2011-08-31
2011-09-30   2011-09-30
2011-10-31   2011-10-31
2011-11-30   2011-11-30
2011-12-31   2011-12-31
Freq: M, dtype: datetime64[ns]

You can get just the month and day like this (see this site for a summary of strftime)

您可以获得这样的月份和日期(请参阅此站点以获取摘要strftime

s.dt.strftime('%m-%d')

2011-01-31    01-31
2011-02-28    02-28
2011-03-31    03-31
2011-04-30    04-30
2011-05-31    05-31
2011-06-30    06-30
2011-07-31    07-31
2011-08-31    08-31
2011-09-30    09-30
2011-10-31    10-31
2011-11-30    11-30
2011-12-31    12-31
Freq: M, dtype: object