【发布时间】:2017-10-30 15:25:35
【问题描述】:
在我的数据框中,我有一列将包含一个日期。仅当格式为“YYYYMMDD”或“MMDD”时才应被接受。另外,如果格式是'MMDD',年份应该从另一列中取出并附加到MMDD日期中,如下所示;
df['YYYYMMDD'] = df['YYYY'].astype(str) + df['Date'].astype(str).apply(lambda x: x.zfill(4))
追加后,旧列被删除,新列重命名为所需的输出。
对于比赛,我尝试了正则表达式 (df_ori['Date'].str.matches(r'^\d{8}$')) 但我得到了错误;
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas。
我尝试df_ori['Date'].astype(str).str.matches(r'^\d{8}$'),它给出了错误;
'StringMethods' object has no attribute 'matches'
我认为我只是以错误的方式解决这个问题。任何帮助表示赞赏。
df.head() 按要求:
YYYY MMDD
0 2016 525
1 2016 728
2 2014 821
3 2016 311
4 2016 422
【问题讨论】:
-
列值是字符串还是日期时间对象?请发布
df.head()或一个最小示例。 -- minimal reproducible example -
列值是整数。我会将 df.head() 添加到主帖中。
标签: python regex pandas dataframe