【问题标题】:Pandas - check if values in column match one of two formatsPandas - 检查列中的值是否匹配两种格式之一
【发布时间】: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


【解决方案1】:

你需要str.matchstr.zfill

df['YYYYMMDD'] = df['YYYY'].astype(str) + df['Date'].astype(str).str.zfill(4)

print (df_ori['YYYYMMDD'].astype(str).str.match(r'^\d{8}$'))
0    True
1    True
2    True
3    True
4    True
Name: YYYYMMDD, dtype: bool

如果想要48 匹配:

print (df_ori['YYYYMMDD'].astype(str).str.match(r'^\d{8}$|^\d{4}$'))

如果想从 4 到 8 匹配:

print (df_ori['YYYYMMDD'].astype(str).str.match(r'^\d{4,8}$'))

编辑:

仅当 len 为 4 时才需要追加:

print (df_ori)
   YYYY  MMDD  YYYYMMDD
0  2016   525  20160525
1  2016   728  20160728
2  2014  1121      1121
3  2016  1211      2211
4  2016   422  20160422

a = df_ori['YYYY'].astype(str) + df_ori['YYYYMMDD'].astype(str)
m = df_ori['YYYYMMDD'].astype(str).str.len() == 4
df_ori['YYYYMMDD'] = df_ori['YYYYMMDD'].mask(m, a)
print (df_ori)
   YYYY  MMDD  YYYYMMDD
0  2016   525  20160525
1  2016   728  20160728
2  2014  1121  20141121
3  2016  1211  20162211
4  2016   422  20160422

【讨论】:

  • 匹配 YYYYMMDD 格式,但也可以是 MMDD,如果是这种情况,我需要从第二列追加年份。
猜你喜欢
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2017-11-30
  • 1970-01-01
相关资源
最近更新 更多