【问题标题】:Why do I get 0 when dividing two numbers?为什么两个数相除得到0?
【发布时间】:2017-03-14 05:56:46
【问题描述】:

我试图找到陆地面积与水域面积的比率,但当我尝试将这两个数字相除时得到 0:

import pandas as pd
import sqlite3
import math
conn = sqlite3.connect('factbook.db')
query = "SELECT SUM(area_land ) from facts WHERE area_land != '';"
query2 = "SELECT SUM(area_water) from facts WHERE area_water != '';"
area_land= pd.read_sql_query(query,conn)
#print(area_land.iloc[0])
area_water= pd.read_sql_query(query2,conn)
ratio = area_land.iloc[0]/area_water.iloc[0]
print(ratio)

我必须将 ratio 初始化为 float 类型吗?

这是两个变量的输出:

SUM(area_land )    128584834                                                    
Name: 0, dtype: int64                                                           
SUM(area_water)    4633425                                                      
Name: 0, dtype: int64   

【问题讨论】:

  • 您使用的是 Python 2 还是 Python 3?
  • 请改用 float(num1)/float(num2)float(num1)/num2num1/float(num2)。 2 的除法 int 在 Python 2 中为您提供另一个 int
  • area_land.iloc[0]area_water.iloc[0]的值是多少?
  • @Macin 我在我的问题中添加了输出

标签: python sql sqlite pandas dataframe


【解决方案1】:

正如 cmets 中提到的,python 3 将执行 from __future__ import division 因此在除以两个整数时不应得到零。如果是python 2,可以在文件顶部添加from __future__ import division,或者将列设为floatarea_water.your_column = area_water.your_column.astype(float)

【讨论】:

    【解决方案2】:

    您正在将一个整数除以另一个整数。当您这样做时,结果将作为整数传递。比如1/2 = 0.5,但是0.5表示成整数就是0。

    将分子或分母中的一个或两个转换为 float 以返回浮点数。

    【讨论】:

      【解决方案3】:

      你选择了结果row做除法,你应该用.iloc[0,0]选择实际值:

      ratio = area_land.iloc[0,0] / area_water.iloc[0,0]
      

      【讨论】:

        【解决方案4】:

        我建议您使用更高效的 SQL 方法 - 您可以使用一条 SQL 语句实现您的目标:

        import pandas as pd
        import sqlite3
        
        conn = sqlite3.connect(r'd:/temp/test.sqlite3')
        query = "select sum(coalesce(area_land,0))*1. / sum(coalesce(area_water,0))*1. as ratio" + \
                " from facts where area_land is not null or area_water is not null"
        
        ratio = pd.read_sql(query, conn).iloc[0, 0]
        
        print('Ratio: {}'.format(ratio))
        

        输出:

        Ratio: 0.75
        

        设置:

        C:\sqlite3 d:\temp\test.sqlite3
        create table facts(area_land int, area_water int);
        insert into facts values (NULL, 10);
        insert into facts values (10, NULL);
        insert into facts values (5, 10);
        .quit
        

        数据:

        sqlite> .mode column
        sqlite> .header on
        sqlite> .nullvalue NULL
        sqlite> select * from facts;
        area_land   area_water
        ----------  ----------
        NULL        10
        10          NULL
        5           10
        

        【讨论】:

          猜你喜欢
          • 2019-10-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-07
          • 2023-03-06
          相关资源
          最近更新 更多