首页 > 解决方案 > 选择要通过动态列名更改的列值

问题描述

我有一个包含多个日期时间列的数据框,但它们有不同的格式。我想让它们正常化。但是,相应的列名是动态的,只有其中一部分是常量,例如xxx last updatedyyy updated,其中字符串部分updated始终指示列是日期时间类型。

我怎么能动态.apply(pd.to_datetime)到所有这些列?

到目前为止,我在其他线程中找到的所有解决方案都需要指明特定的列名。

标签: python-3.xpandas

解决方案


列名是一个索引,因此您可以像过滤行一样过滤它们。

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')

推荐阅读