【问题标题】:Python convert multiple columns to datetime using for loopPython使用for循环将多列转换为日期时间
【发布时间】:2021-05-17 06:18:42
【问题描述】:

我被困在这个问题上并寻求社区帮助。我在数据框中有几列被标记为对象,但想转换为日期时间。所有列都有年、月、日标准。

time = np.array(['time1','time2','time3'])
def cols_to_datetime(df):

   cols_to_datetime = time

   for col in cols_to_datetime:
       df[col] = pd.to_datetime(df[col])

   return df

虽然都有年、月、日,但我收到了这个错误

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

df-

time1                      time2                      time3 
2020-06-06 20:01:10.327    2020-06-06 22:08:14.832    2020-06-06

df 中可能存在需要跳过的空值。

我在没有他们的情况下进行了测试,但没有运气。所以我不太确定为什么这种方法不起作用。谢谢!

【问题讨论】:

  • 请发布您的数据框示例
  • 当心使用 time 之类的变量名称...而且它会是特定于数据的
  • 我添加了一个简化的 df 示例

标签: python pandas function datetime for-loop


【解决方案1】:

您可以使用DataFrame.astype()。

import pandas as pd

def convert_times(df, cols=None):
    if not cols:
        # if no columns are specified, use all
        cols = df.columns
    df[cols] = df[cols].astype('datetime64')
    return df

df = pd.DataFrame({
    'created_at': ['2020-06-06 20:01:10.327'],
    'updated_at': ['2020-06-06 22:08:14.832']
})
print(df.dtypes)
# created_at    object
# updated_at    object
# dtype: object

df2 = convert_times(df)
print(df2.dtypes)
# created_at    datetime64[ns]
# updated_at    datetime64[ns]
# dtype: object

【讨论】:

  • 如果其中一个 dfs 没有所有的列,我该如何轻松解决这个问题?
  • 您的意思是您的数据框有很多列,但您只想将其中的一部分放入日期时间?使用convert_times(df, ['col1', 'col2'])。不会触及数据框的所有其他列。
  • 如果一个 df 只有 time1 而另一个 df 有 time1,time2,time3。我在几个 dfs 上运行它,所以如果不是所有时间列都在 df 中,我会得到一个 not in index 错误
  • 那么你将不得不使用convert_times(df1, ['time1', 'time2']); convert_times(df2, ['anothertime1', 'anothertime2'])
猜你喜欢
  • 1970-01-01
  • 2019-07-17
  • 2020-07-06
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多