【问题标题】:how to sort from greatest to least in a .csv file in python如何在python中的.csv文件中从最大到最小排序
【发布时间】:2018-02-22 16:13:17
【问题描述】:

您好,我目前正在尝试对 .csv 中的数据进行排序,以了解每个月的平均降雪量,然后选择前三名。这是我到目前为止的代码。我认为我可以通过使用变量对数据进行排序,然后在下一行调用排序后的变量,但这不起作用。相反,我得到一个 TypeError: Can't convert 'list' object to str 隐式。非常感谢任何指导。

谢谢。

import os
import csv
data = open('filteredData.csv','r')
# Create Dictionaries to store location values
# Snow_Fall is the number of inches for that location
# Number_Days is the number of days that there is Snowfall data for
Snow_Fall = {}
Number_Days = {}

# Create CSV reader
csv1 = csv.DictReader(data,delimiter=',')
# read each row of the CSV file and process it
for row in csv1:
    # Check the date column and see if it is in 2017
    if "2017" in row["DATE"]:
        # Split the date into Month, Day and Year
        Month, Day, Year = row["DATE"].split("/")
        # Check to see if the value in the snow column is null/none if so then skip processing that row
        if (row["SNOW"] is None) or (row["SNOW"] == ""):
            pass
        else:
            # Check to see if the location has been added to the dict if it has then add the data to itself
            # If it has not then just assign the data to the location.
            # Concat the Location and Month together to get a unique location per month
           # print (" The location is ==> " + row["NAME"] + " <<++>> The Month is " + str(Month))
            name_date = row["NAME"] + "_" + str(Month)
            if name_date in Snow_Fall:
                Snow_Fall[name_date] = Snow_Fall[name_date] + float(row["SNOW"])
                Number_Days[name_date] = Number_Days[name_date] + 1

            else:
                Snow_Fall[name_date] = float(row["SNOW"])
                Number_Days[name_date] = 1

# For each location we want to print the data for that location
for location in Snow_Fall:
   # split the location into Name and month
   location_name, location_date = location.split("_")
   #print ("The number of inches for location " + location_name + " in the Month of " + location_date + " is " + str(Snow_Fall[location]))            
   #print ("The number of days of snowfall for location " + " in the Month of " + location_date+ location_name + " is " + str(Number_Days[location]))
   #print ("The average Number of Inches for location " + location_name + " in the Month of " + location_date + " is " + str(Snow_Fall[location] / Number_Days[location]))

# Check if file exists then remove it if it does   
if (os.path.isfile('average2017.csv')):
   os.remove('average2017.csv')
# Open file   
data2 = open('average2017.csv','w')
# Write File headers
data2.write("Location, Month, Average Snow Fall \n")
# Write contents of the file
for location in Snow_Fall:
    # SPlit the location into name and month
    location_name, location_date = location.split("_")
    average = str(Snow_Fall[location] / Number_Days[location])
    newaverage = sorted([average])
    data2.write('"' + location_name + '",' + location_date + "," + newaverage + "\n")
# Close the open files
data2.close()
data.close()

以下信息来自测试

runfile('U:/CISP253/Final/temp.py', wdir='U:/CISP253/Final') 地点月份\ 0 斯巴达 2.8 瓦,美国密歇根州 8
1 斯巴达 2.8 瓦,美国密歇根州 9
2 美国密歇根州罗克福德 12
美国密歇根州罗克福德 3 号 11
4 肯特伍德 1.6 WSW,美国密歇根州 2
5 斯巴达 2.8 W,美国密歇根州 5
6 斯巴达 2.8 W,美国密歇根州 6
7 SPARTA 2.8 W,美国密歇根州 7
8 肯特伍德 1.6 WSW,美国密歇根州 5
9 COMSTOCK PARK 3.7 NNE,美国密歇根州 12
10 喀里多尼亚 4.4 WNW,美国密歇根州 9
11 COMSTOCK PARK 3.7 NNE,美国密歇根州 10
12 大急流城 4.6 ESE,美国密歇根州 12
13 ROCKFORD 0.9 NNE,美国密歇根州 5
14 大急流城 4.6 ESE,美国密歇根州 10
15 大急流城 4.6 ESE,美国密歇根州 11
16 喀里多尼亚 4.4 WNW,美国密歇根州 3
17 喀里多尼亚 4.4 WNW,美国密歇根州 2
18 喀里多尼亚 4.4 WNW,美国密歇根州 1
19 喀里多尼亚 4.4 WNW,美国密歇根州 7
20 喀里多尼亚 4.4 WNW,美国密歇根州 6
21 喀里多尼亚 4.4 WNW,美国密歇根州 5
22 喀里多尼亚 4.4 WNW,美国密歇根州 4
23 ROCKFORD 5.0 ESE,美国密歇根州 8
24 罗克福德,美国密歇根州 7
25 罗克福德,美国密歇根州 4
26 罗克福德,美国密歇根州 5
27 罗克福德,美国密歇根州 2
28 罗克福德,美国密歇根州 3
29 大急流城 2.9 NW,美国密歇根州 4
.. ... ...
215 艾伦代尔 1.3 SSW,美国密歇根州 11
216 贝尔蒙特 1.0 WNW,美国密歇根州 2
217 贝尔蒙特 1.0 WNW,美国密歇根州 5
218 贝尔蒙特 1.0 WNW,美国密歇根州 4
219 贝尔蒙特 1.0 WNW,美国密歇根州 7
220 贝尔蒙特 1.0 WNW,美国密歇根州 6
221 贝尔蒙特 1.0 WNW,美国密歇根州 9
222 贝尔蒙特 1.0 WNW,美国密歇根州 8
223 大急流城 2.5 ENE,美国密歇根州 7
224 杰尼森 1.0 NE,美国密歇根州 10
225 杰尼森 1.0 NE,美国密歇根州 11
226 大急流城 GERALD R 福特国际机场... 12
227 大急流城 2.9 NW,美国密歇根州 9
228 大急流城 GERALD R 福特国际机场... 10
229 大急流城 GERALD R 福特国际机场... 11
230 东大急流城,美国密歇根州 12
231 东大急流城,美国密歇根州 11
232 东大急流城,美国密歇根州 10
233 COMSTOCK PARK 3.7 NNE,美国密歇根州 8
234 肯特伍德 1.6 WSW,美国密歇根州 7
235 大急流城 2.5 ENE,美国密歇根州 11
236 杰尼森 1.0 NE,美国密歇根州 8
237 杰尼森 1.0 NE,美国密歇根州 9
238 杰尼森 1.0 NE,美国密歇根州 6
239 杰尼森 1.0 NE,美国密歇根州 7
240 杰尼森 1.0 NE,美国密歇根州 4
241 杰尼森 1.0 NE,美国密歇根州 5
242 COMSTOCK PARK 3.7 NNE, MI US 11
243 COMSTOCK PARK 1.0 NNW, MI US 7
244 ADA 1.8 W,美国密歇根州 1

  AverageSnowFall   

0 0.000000
1 0.000000
2 0.948387
3 0.400000
4 0.000000
5 0.000000
6 0.000000
7 0.000000
8 0.000000
9 1.150000
10 0.000000
11 0.000000
12 2.390000
13 0.000000
14 0.000000
15 0.025000
16 0.408696
17 0.816667
18 0.647826
19 0.000000
20 0.000000
21 0.000000
22 0.415000
23 0.000000
24 0.000000
25 0.900000
26 0.000000
27 1.020000
28 0.928571
29 0.362500
.. ...
215 0.050000
216 0.172727
217 0.025000
218 0.000000
219 0.000000
220 0.000000
221 0.000000
222 0.000000
223 0.000000
224 0.000000
225 0.000000
226 1.193548
227 0.000000
228 0.000000
229 0.026667
230 1.264516
231 0.033333
232 0.000000
233 0.000000
234 0.000000
235 1.000000
236 0.000000
237 0.000000
238 0.000000
239 0.000000
240 0.000000
241 0.000000
242 0.000000
243 0.000000
244 0.609677

[245 行 x 3 列] Traceback(最近一次调用最后一次):

文件“”,第 1 行,在 runfile('U:/CISP253/Final/temp.py', wdir='U:/CISP253/Final')

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 705 行,在运行文件中 execfile(文件名,命名空间)

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”,第 102 行,在 execfile exec(编译(f.read(),文件名,'exec'),命名空间)

文件“U:/CISP253/Final/temp.py”,第 5 行,在 data = data.sort_values(by=['AverageSnowFall'])

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py”,第 3619 行,在 sort_values k = self.xs(by, axis=other_axis).values

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py”,第 2335 行,在 xs 返回自我[key]

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py”,第 2139 行,在 getitem 中 return self._getitem_column(key)

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py”,第 2146 行,在 _getitem_column return self._get_item_cache(key)

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py”,第 1842 行,在 _get_item_cache values = self._data.get(item)

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\internals.py”,第 3843 行,在获取 loc = self.items.get_loc(item)

文件“C:\Users\dwillaford\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py”,第 2527 行,在 get_loc return self._engine.get_loc(self._maybe_cast_indexer(key))

文件“pandas/_libs/index.pyx”,第 117 行,在 pandas._libs.index.IndexEngine.get_loc 中

文件“pandas/_libs/index.pyx”,第 139 行,在 pandas._libs.index.IndexEngine.get_loc 中

文件“pandas/_libs/hashtable_class_helper.pxi”,第 1265 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 中

文件“pandas/_libs/hashtable_class_helper.pxi”,第 1273 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 中

KeyError: 'AverageSnowFall'

【问题讨论】:

  • 要处理此类表格和数据框,强烈建议使用pandas
  • 有没有办法做到这一点而不必使用熊猫?这样我就不必重写所有内容了?
  • 可能,但 pandas 只需要大约 5 行。
  • 另外:您是否正在寻找每月降雪量最多的 3 个地点?还是只有 3 个地点在任何月份降雪量最多?
  • 3 最高的任何一个月我认为一旦我从大到小排序后我可以阅读前 3 行

标签: python


【解决方案1】:

这个例子是为使用Pandas dataframe 量身定做的。您可以将 csv 读入数据框,按不同列的值排序,获取数据框的子集等。这就是我为您的示例所做的:

import pandas as pd
data = pd.read_csv('filteredData.csv')
# Sort dataframe by Average Snow Fall column
data = data.sort_values(by=['Average Snow Fall'])
# Get the top 3 locations by average snow fall
print data['Location'].iloc[:3]

【讨论】:

  • 我收到“平均降雪量”的关键错误,我按照您的设置进行了操作。唯一不同的是我使用了 data = pd.read_csv('average2016.csv')。我确实创建了一个新文件,而不是将其添加到我已有的文件中。
  • 尝试在 read_csv 之后打印数据帧 - 正确读取标题可能存在问题。实际上,在查看它之后,我敢打赌它正在创建三列,一个名为“Average”,另一个名为“Snow”,另一个名为“Fall”。取出空格再试一次
  • 那么我该如何防止这种情况发生呢?
  • 去掉标题中的空格
  • 不,这仍然会产生一个关键错误...抱歉这么多问题我是 python 的新手。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多