首页 > 解决方案 > 如何覆盖基于 df.loc 的数据框列并使用日期时间映射

问题描述

我需要将整数转换为数据框列中的日期时间对象,其中该列具有混合数据类型。要知道是否应用该功能,我需要引用不同的列。

我已经能够通过将数据框转换为字典并遍历它来解决这个问题,但是当数据变得太大时需要太长时间。

当我尝试使用 .loc 和 .map 解决这个问题时,只有当我没有设置相等时它才会给出正确的输出。

这是我的数据框。

df = pd.DataFrame([
    {'data' : 'abc', 'type': 'string'},
    {'data' : 1559347200000, 'type': 'int'},
    {'data': pd.to_datetime(1559347200000, unit='ms'), 'type':'datetime'}
    ])

当我运行它时,数据框的行为符合预期。Column: 'data' 具有混合类型,并且 column: 'type' 我创建的目的是让我知道列 'data' 中的内容。

现在我需要将 'data' 转换为 'type' = 'int' 的日期时间对象。

df.loc[df['type']=='int', 'data'].map(lambda x:pd.to_datetime(x,unit='ms'))

这个带有 dtype: datetime64 的“2019-06-01”的输出看起来是正确的。

但是,当我将其设置为等于自身时,使用:

df.loc[df['type']=='int', 'data'] = df.loc[df['type']=='int', 'data'].map(lambda x:pd.to_datetime(x,unit='ms'))

然后调用:

df.loc[df['type']=='int', 'data']

我得到 1559347200000000000 的输出

为什么在这种情况下它不返回“2019-06-01”?

标签: pythonpandas

解决方案


不要检查“类型”列是什么,然后根据您在“类型”列中找到的内容将更改应用于“数据”列,而是执行快捷方式。检查 lambda 表达式中“数据”列中值的类型,如果它是 int 类型,则转换为 datetime,否则不改变。

df=df.applymap(lambda x: pd.to_datetime(x,unit='ms') if type(x) is int else x)

输出:

                  data      type
0                  abc    string
1  2019-06-01 00:00:00       int
2  2019-06-01 00:00:00  datetime

推荐阅读