【问题标题】:python - creating dictionary from excel using specific columnspython - 使用特定列从excel创建字典
【发布时间】:2015-11-23 19:22:32
【问题描述】:

我对 python 比较陌生(在 GIS 世界之外)并且正在努力获取我不会为我正在使用 USGS 地震数据做的副项目的代码。数据在一个包含 7 列的 excel 文件中,如下所示:

USGS earthquake table

我有这些我自己设定的任务:

  1. 地震总数
  2. 创建地区地震时间词典
  3. 地震频率最高的前 3 个地点
  4. 地震震级最高的前 3 个地点
  5. 将以上内容打印到文本文件中

我被困在第二个任务上,一旦我完成了剩下的工作。

另外,我知道尚未将任何内容打印到文本文件中!

import xlrd
from xlrd import open_workbook
from collections import Counter

def get_sheet(xl_file):
    wb = open_workbook(xl_file,'r')

    # get first sheet in the workbook
    return wb.sheets()[0]

def number_eq(sheet):
    row_count = len(range(sheet.nrows))
    print ("Total number of earthqaukes = %s") % row_count

def no_earthquake_region():

    #???

#def top_freq_eq(sheet):

    #print (Counter(words).most_common(5))

#def top_mag_eq(sheet):

    #print (Counter(words).most_common(5))

def main(xl_file, out_folder):

    sheet = get_sheet(xl_file)
    row = number_eq(sheet)


if __name__ == "__main__":
    xl_file = r'D:\Projects\Other\data\EarthquakeUSGS.xlsx'
    out_folder = r"D:\Projects\Other\data\output\output.txt"
    main(xl_file, out_folder)
    print("Done!")

【问题讨论】:

    标签: python excel dictionary xlrd


    【解决方案1】:

    我会这样做:

        import xlrd
        from xlrd import open_workbook
        from collections import Counter
    
        def get_sheet(xl_file):
            wb = open_workbook(xl_file,'r')
    
            # get first sheet in the workbook
            return wb.sheets()[0]
    
        def number_eq(sheet):
            row_count = len(range(sheet.nrows))
            print ("Total number of earthqaukes = %s") % row_count
    
        def no_earthquake_region(sheet):
            l = []
            num_of_rows = sheet.nrows
            num_of_cols = sheet.ncols
            if(num_of_rows > 1):
                d={}
                for i in range(2,num_of_rows):
                    d = {"Time":sheet.cell(i,1).value , "Region":sheet.cell(i,6).value}
                    l.append(d)
            return l
    
        #def top_freq_eq(sheet):
    
            #print (Counter(words).most_common(5))
    
        #def top_mag_eq(sheet):
    
            #print (Counter(words).most_common(5))
    
        def main(xl_file, out_folder):
    
            sheet = get_sheet(xl_file)
            row = number_eq(sheet)
            print no_earthquake_region(sheet)
    
    
        if __name__ == "__main__":
            xl_file = r'D:\Projects\Other\data\EarthquakeUSGS.xlsx'
            out_folder = r"D:\Projects\Other\data\output\output.txt"
            main(xl_file, out_folder)
            print("Done!")
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2018-04-27
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多