python - 如何覆盖基于 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”?
解决方案
不要检查“类型”列是什么,然后根据您在“类型”列中找到的内容将更改应用于“数据”列,而是执行快捷方式。检查 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
推荐阅读
- python - 将分区 Parquet 文件读取到 Python 中的 DataFame(在内存中),其中列类型是数组的数组
- asp.net-core - 找不到 Asp.net 核心身份模型命名空间名称
- python - 用python中给定字符串中的其他字符替换指定字符
- excel - 如何调整我的 VBA 代码以检查文件名是否已被占用?
- python - 如何添加两个列表 - 一个带有正号,一个带有负号
- kubernetes - 在入口资源中找不到端点“default-http-backend”
- javascript - 如何在javascript客户端将图像解析为ICO格式
- multithreading - 来回切换上下文的最简单方法(调度)
- c++ - 为什么 Vector 不存储字符串?(阿杜诺)
- google-cloud-platform - 无法访问 GCP 深度学习 VM 上的 Jupyter Notebook 实例