【问题标题】:Python AttributeError: Can only use .str accessor with string valuesPython AttributeError:只能使用带有字符串值的 .str 访问器
【发布时间】:2020-03-27 03:16:14
【问题描述】:
flights['Duration']=flights['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

但是我收到此错误消息:

AttributeError                            Traceback (most recent call last)
    <ipython-input-24-45eafc3e9d23> in <module>()
    ----> 1 travel['Duration']=travel['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)
          2 
    3 frames
    /usr/local/lib/python3.6/dist-packages/pandas/core/strings.py in _validate(data)
       1965 
       1966         if inferred_dtype not in allowed_types:
    -> 1967             raise AttributeError("Can only use .str accessor with string " "values!")
       1968         return inferred_dtype
       1969 

    AttributeError: Can only use .str accessor with string values!

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

您的航班['Duration'] 列似乎没有字符串值(可能是 int64 或 float64)。

import pandas as pd
df = pd.DataFrame(data=[(1, '12h 50m'), (2, '1h 12m')], columns=['id', 'Duration'])
df['Duration']=df['Duration'].str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

结果:

   id  Duration
0   1       770
1   2        72

这很好用,因为当我们创建数据框时 - 第二列值是字符串类型。如果我们的基础数据不一致,所以我们应该小心结果,这可能会产生误导。示例:

df = pd.DataFrame(data=[(1, 123), (2, 0.123), (3, '12h 30m')], columns=['id', 'Duration'])
df['Duration']=df['Duration'].astype(str).str.replace('h','*60').str.replace(' ','+').str.replace('m','*1').apply(eval)

结果:

   id  Duration
0   1   123.000
1   2     0.123
2   3   750.000

在这个例子中,我们使用了.astype(str),但正如我们所见,如果数据有各种数据类型 - 结果可能真的是错误的。因此,请检查您的数据源中的数据框,然后再次尝试转换数据:)

【讨论】:

    【解决方案2】:

    你可能想做的更像是:

    flights['Duration'] = pd.to_timedelta(flights['Duration']).seconds//60
    

    这会将时间字符串直接转换为分钟

    您尝试使用的方法,apply(eval) 似乎。 . . very unsafe.

    【讨论】:

      【解决方案3】:

      您应该首先使用 astype(str) 将字符串转换为列。

      【讨论】:

        猜你喜欢
        • 2021-03-18
        • 2018-12-22
        • 2017-06-01
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        相关资源
        最近更新 更多