1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > c#将字符串转换为数组_pandas入门: 时间字符串转换为年月日

c#将字符串转换为数组_pandas入门: 时间字符串转换为年月日

时间:2021-01-14 03:38:58

相关推荐

c#将字符串转换为数组_pandas入门: 时间字符串转换为年月日

pandas中时间字符串转换为年月日方法总结。

创建一个dataframe

df = pd.DataFrame(['-12-09', '-12-02'], columns=["date"])

方法1:先转换为时间类型,在获取年月日

# 转换为时间类型df["date"] = pd.to_datetime(df["date"], format='%Y-%m-%d')# 获取年df["year"] = pd.to_datetime(df["date"]).dt.year# 获取月df["month"] = pd.to_datetime(df["date"]).dt.month# 获取日df["day"] = pd.to_datetime(df["date"]).dt.day# 获取周df["week"] = pd.to_datetime(df["date"]).dt.weekprint(df)print(df.dtypes)

结果如下:

date year month day week0 -12-09 12 9 501 -12-02 12 2 49datedatetime64[ns]year int64month int64dayint64week int64dtype: object

方法2

# 转换为时间df["date"] = pd.to_datetime(df["date"])# 获取年月日df["year-month-day"] = df["date"].apply(lambda x: x.strftime("%Y-%m-%d"))# 获取年df["year"] = df["date"].apply(lambda x: x.strftime("%Y"))# 获取月df["month"] = df["date"].apply(lambda x: x.strftime("%m"))# 获取日df["day"] = df["date"].apply(lambda x: x.strftime("%d"))# 获取月日df["month-day"] = df["date"].apply(lambda x: x.strftime("%Y-%m"))# 获取周df['week'] = df['date'].apply(lambda x: x.strftime('%W'))print(df)print(df.dtypes)

结果如下:

date year-month-day year month day month-day week0 -12-09-12-09 12 09 -12 491 -12-02-12-02 12 02 -12 48date datetime64[ns]year-month-day objectyear objectmonth objectday objectmonth-day objectweek objectdtype: object

欢迎关注,一起学习

参考:

/bravesunforever/p/11219299.html/jingjing_94/article/details/89195791

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。