【问题标题】:Python: how to read csv file and store in dictionary that has the string key and float valuePython:如何读取 csv 文件并存储在具有字符串键和浮点值的字典中
【发布时间】:2020-12-17 04:09:31
【问题描述】:

我想编写一个 Python 程序来读取 csv 文件并存储在具有字符串键和浮点值的字典中。使用字典中的数据存储,我想计算平均幅度和深度。

aver_quake[k] = sum(v) / float(len(v))

以下是错误:

TypeError: +: 'int' 和 'str' 的操作数类型不受支持

地震.csv 文件示例

当地时间、幅度、深度 2020/03/18 08:57:41 MDT,3.6,8.3 2020/03/18 07:36:38 MDT,3.5,9.6 2020/03/21 10:59:31 MDT,3.4,10.3 2020/03/18 13:07:30 MDT,3.4,9

class Quake_Reader:

    def __init__(self, mag, dep, __location = 'city'):
        self.depth = dep
        self.magnitude = mag
        self.location = __location

    def __get_location(self):
        return self.location

    def get_magnitude(self, __magnitude):
        return __magnitude

    def get_depth(self, __depth):
        return __depth

    """ Total Quake method calculate the total size in the data """
    def total_quake(self):
        return len(quake_list) - 1
        # print("There are {} shakes in the data".format(len(quake_list) - 1))
        # print("---" * 15)

    """ String method call the total quake method print out the size of data"""
    def __str__(self):
        print("Total quakes in the data is: ", self.total_quake())
        print("---" * 12)

    """ Top ten magnitude"""
    def top_ten(self):
        k = Counter(quake_list)
        high = k.most_common(10)
        print("Top 10 largest quakes in the data are: ")
        print("-"*38)
        [print(key, value) for key, value in high]

    """ Average magnitude method"""
    def avg_magn(self):
        aver_quake = {}
        for k, v in quake_list.items():
            aver_quake[k] = sum(v) / float(len(v))
    
""" Main function """
if __name__ == '__main__':
    # instantiate quake reader class
    qr = Quake_Reader(0,0,"city")
    try:
        # create an empty dictionary
        quake_list = dict()
        # open the source data
        with open('earthquakes.csv', 'r') as csv_file:
            # loop through the file and store the data in an empty quake
            # dictionary
            for key, value in enumerate(csv_file):
                line, *lines = value.split(",")
                if line in quake_list:
                    quake_list[key] = lines
                else:
                    quake_list[line] = lines
            # closed the input file
            csv_file.close()
    except FileNotFoundError:
        print("File doesn't exist.")
        exit()

谢谢!

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    当您存储幅度和深度的值时,您将它们存储为字符串。

    因此,当您尝试计算总和时,解释器会告诉您 + 不支持 intstr。要解决此问题,您可以在检索这些值时将它们转换为 int

    for key, value in enumerate(csv_file):
        # value.split(",") gives you string instead of int
        line, *lines = value.split(",")
    
        # Convert each element in lines to float
        try:
            lines = [float(v) for v in lines]
        except:
            pass
    
        if line in quake_list:
            quake_list[key] = lines
        else:
            quake_list[line] = lines
    

    【讨论】:

    • 嗨。谢谢你解释这个问题。我能够将字符串转换为大小和深度的浮点数。我试图找出平均幅度和深度。数据存储在以本地时间(日期和时间)为键、幅度和深度为 2 个值的字典中。数据集有 730 次震动,震级大小为 41。同一震级出现多次。例如,3.4级在不同深度水平发生了6次,平均为8.82km。 Excel计算显示平均震级为2.08,平均深度为7.27km。 2个方法怎么写?
    猜你喜欢
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2013-03-02
    相关资源
    最近更新 更多