【问题标题】:When does this <class 'str'> become a <class 'decimal.Decimal'>?这个<class 'str'> 什么时候变成<class 'decimal.Decimal'>?
【发布时间】:2021-06-23 04:57:50
【问题描述】:

这个:

cur.execute("SELECT site_number, site_name, latitude FROM mydb.station ORDER BY site_number")

rows = pd.DataFrame(cur.fetchall(), columns=['site_number', 'site_name', 'latitude'])
for item in rows.columns:
    print(item, type(item))

生产:

site_number <class 'str'>
site_name <class 'str'>
latitude <class 'str'>

但到时候:

length_hours = day_length(day, v.latitude)

def day_length(day_of_year, latitude):
    ic(type(day_of_year), day_of_year, type(latitude), latitude)

结果如下:

ic| type(day_of_year): <class 'int'>
    day_of_year: 1
    type(latitude): <class 'decimal.Decimal'>
    latitude: Decimal('-14.3')

我错过了什么? type(item) not 是否返回实际的数据类型?稍后会发生转换吗?

我只是想了解发生了什么。

为了说明错误,这是我正在尝试修复的...

当它到达时:

p = math.asin(0.39795 * math.cos(0.2163108 + 2 * math.atan(0.9671396 * math.tan(.00860 * (day_of_year - 186)))))
ic(p)
pi = math.pi
ic(type(pi), pi)
day_light_hours = 24 - (24 / pi) * math.acos(
    (math.sin(0.8333 * pi / 180) + math.sin(latitude * pi / 180) * math.sin(p)) / (
            math.cos(latitude * pi / 180) * math.cos(p)))

我明白了:

ic| p: -0.40270065067443084
ic| type(pi): <class 'float'>, pi: 3.141592653589793
unsupported operand type(s) for *: 'decimal.Decimal' and 'float'

附:我没有在 day_length 函数中编写数学运算,因此无法更改其中的任何内容。

【问题讨论】:

  • for item in rows.columns 只是循环遍历 列名,它们是字符串,而不是值...!?

标签: python type-conversion


【解决方案1】:

啊。我现在意识到我以为我找到了“如何识别列数据类型”的解决方案,但实际上并非如此。

我应该一直在寻找 dtype。

pandas how to check dtype for all columns in a dataframe?

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多