【问题标题】:Converting dates with condition带条件转换日期
【发布时间】:2022-11-24 10:25:06
【问题描述】:

我正在尝试转换一列日期。有以“ms”为单位的日期和时间戳,我也想在时间戳中以“ms”为单位转换这些日期。所以,我创建了这个函数:

def convert(df):
  if df[df['Timestamp'].str.contains(':') == False]:
     df.Timestamp = pd.to_datetime(df.Timestamp, unit='ms')
return df

df = convert(df)

但是出现此错误:ValueError:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我也尝试使用 np.where 但没有用......

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您的 == False 语句适用于整个数据框/系列,而不仅仅是您想要的行,因此您可以做的只是使用 .loc 将函数应用于这些行:

    def convert(df):=
      condition = ~df.Timestamp.str.contains(":") #where this field DOESN'T contain ":"
      df.loc[condition, 'Timestamp'] = 
             pd.to_datetime(df.loc[condition, 'Timestamp'], unit='ms')
    return df
    
    df = convert(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多