【问题标题】:Splitting Text to get year拆分文本以获取年份
【发布时间】:2020-12-08 04:03:34
【问题描述】:

如何从列发布日期(例如:1995 年 1 月 1 日)中的所有数据中提取年份并分配给同一数据框中的“年份”列?

建议的一种方法是使用 split str.split() 方法。

    movie id    movie title release date    unknown Action  Adventure   Animation   Childrens   Comedy  Crime   ... Film-Noir   Horror  Musical Mystery Romance Sci-Fi  Thriller    War Western movie genre
0   1   Toy Story   01-Jan-1995 0   0   0   1   1   1   0   ... 0   0   0   0   0   0   0   0   0   3
1   2   GoldenEye   01-Jan-1995 0   1   1   0   0   0   0   ... 0   0   0   0   0   0   1   0   0   3
2   3   Four Rooms  01-Jan-1995 0   0   0   0   0   0   0   ... 0   0   0   0   0   0   1   0   0   1
3   4   Get Shorty  01-Jan-1995 0   1   0   0   0   1   0   ... 0   0   0   0   0   0   0   0   0   3
4   5   Copycat 01-Jan-1995 0   0   0   0   0   0   1   ... 0   0   0   0   0   0   1   0   0   3
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
1676    1678    Mat' i syn  06-Feb-1998 0   0   0   0   0   0   0   ... 0   0   0   0   0   0   0   0   0   1
1677    1679    B. Monkey   06-Feb-1998 0   0   0   0   0   0   0   ... 0   0   0   0   1   0   1   0   0   2
1678    1680    Sliding Doors   01-Jan-1998 0   0   0   0   0   0   0   ... 0   0   0   0   1   0   0   0   0   2
1679    1681    You So Crazy    01-Jan-1994 0   0   0   0   0   1   0   ... 0   0   0   0   0   0   0   0   0   1
1680    1682    Scream of Stone (Schrei aus Stein)  08-Mar-1996 0   0   0   0   0   0   0   ... 0   0   0   0   0

【问题讨论】:

标签: python pandas text


【解决方案1】:

你是对的,其中一种方法是使用str.split(...),如下所示:

df["Year"] = df["release date"].str.split("-").str[-1]

或者,您可以使用 pandas 日期时间功能。首先,将数据类型转换为日期时间,然后使用 dt 访问器访问“年份”:

df["Year"] = pd.to_datetime(df["release date"]).dt.year

请注意,第一种方法将导致 "Year" 为字符串,而第二种方法将导致 "Year" 为 int。

【讨论】:

  • 谢谢,这很有帮助
猜你喜欢
  • 2011-12-13
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
相关资源
最近更新 更多