python-3.x - 选择要通过动态列名更改的列值
问题描述
我有一个包含多个日期时间列的数据框,但它们有不同的格式。我想让它们正常化。但是,相应的列名是动态的,只有其中一部分是常量,例如xxx last updated
和yyy updated
,其中字符串部分updated
始终指示列是日期时间类型。
我怎么能动态.apply(pd.to_datetime)
到所有这些列?
到目前为止,我在其他线程中找到的所有解决方案都需要指明特定的列名。
解决方案
列名是一个索引,因此您可以像过滤行一样过滤它们。
cols_to_update = df.columns[df.columns.str.contains('updated')]
df[cols_to_update] = df[cols_to_update].apply(pd.to_datetime)
快速细分:
>>> df.columns
Index(['non interesting', 'xxx last updated', 'yyy updated'], dtype='object')
>>> df.columns.str.contains('updated')
array([ False, True, True])
>>> df.columns[df.columns.str.contains('updated')]
Index(['xxx last updated', 'yyy updated'], dtype='object')
推荐阅读
- r - 如何处理重复并偏爱一个版本,但并非总是如此
- firebase - 错误:没有创建 Firebase 应用“[默认]” - 调用 firebase.initializeapp() - 反应原生 Android
- android - 为什么片段和视图不会混淆?
- python - 在正则表达式中转义正斜杠没有什么效果?
- php - Laravel 雄辩的外表平均分
- c# - 对象类型未实现 IComparable
- php - 致命错误:未捕获的错误:调用未定义的方法 Closure::index() php
- css - 如何将 Flexbox 与 Web 组件和影子 DOM 一起使用
- typescript - 尝试在使用打字稿做出本机反应时导入 gql 文件错误 2307
- python - 网页拒绝连接