【问题标题】:How to convert datatype of multiple columns at once based on pattern如何根据模式一次转换多列的数据类型
【发布时间】:2019-08-28 03:48:40
【问题描述】:

我有一个数据框,其列如下所示

我没有提供虚拟数据,因为问题与数据无关。

我正在尝试将time相关列的数据类型从object更改为datetime类型

这是我尝试过的代码

for c in df1.columns:
   print(type(c))
   if c.contains('time'):
      print(c)
      pd.to_datetime(df[c])

但我收到一条错误消息

'str' 对象没有属性'contains'

但是当我使用 `c.endswith('time') 时,一切正常,如下所示

我尝试使用containscontain,但它不起作用。我犯了什么错误吗?像endswith 这样的属性如何工作,而contains 却不行

【问题讨论】:

  • 迭代pd.DataFrame.columns返回str,它有endswiths但没有contains,这是pandas str访问器的一个方法。另外,我想你想要的是df.filter(like='time')
  • 你介意把它写成答案,让我标记为解决方案吗?
  • 当然。添加了一些示例 sn-p 用于演示:)

标签: python python-3.x string pandas dataframe


【解决方案1】:

pd.DataFrame.columns的迭代返回str,它有endswiths但没有contains,这是pandasstr访问器的一个方法:

import pandas as pd

df = pd.DataFrame(columns=['a', 'btime', 'timec', 'timedtime', 'e'])
for c in df.columns:
    print(type(c), hasattr(c, 'endswith'), hasattr(c, 'contains'))

输出:

# type    endswith contains
<class 'str'> True False
...

另外,df.filter(like='time').columns:

Index(['btime', 'timec', 'timedtime'], dtype='object')

根据需要返回:

喜欢:字符串 保留“like in label == True”的轴上的标签。

【讨论】:

  • 它有效。限时接受答复。已经投票了
猜你喜欢
  • 2011-12-02
  • 1970-01-01
  • 2020-05-06
  • 2019-11-10
  • 2020-01-06
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多