PYTHON:打开一个csv文件和找到一个列中的最大数目和名称assosciated与最简单的方法? [英] PYTHON: Simplest way to open a csv file and find the maximum number in a column and the name assosciated with it?
问题描述
我已经看过这个参考文献,所以请不要引用我。
I have looked at this reference so please do not refer me to it.
查找Python中的.CSV文件中的最大数字我无法将此代码修改为我自己的文档超过一个小时,没有结果。我从该代码得到的最好的是打印出最大值,我有0,这是不正确的。我需要1)在F列找到最大值,(38,332,521)和2)打印出与最大值(加利福尼亚州)相关联的状态。
Find max number in .CSV file in Python I struggled to modify this code to my own document for over an hour with no results. The best I got from that code was printing out maximum value, and I got 0, which is incorrect. I need to 1) find the maximum value in column F, (38,332,521) and 2) print out the state associated with the maximum value (California).
这里是我使用的csv:
https://drive.google.com/open?id=0B29hT1HI-pwxMjBPQWFYaWoyalE
Here is the csv I'm using: https://drive.google.com/open?id=0B29hT1HI-pwxMjBPQWFYaWoyalE
这是代码I'我想出了自己,任何帮助/反馈将不胜感激!
This is the code I've come up with myself, any help/feedback would be appreciated!
def largestState():
INPUT = "statepopulations.csv"
COLUMN = 5 # 6th column
with open(INPUT, "rU") as csvFile:
theFile = csv.reader(csvFile)
header = next(theFile, None) # skip header row
pop = [float(row[COLUMN]) for row in theFile]
max_pop = max(pop)
print max_pop
largestState()
推荐答案
max
函数应该为你处理。在我的下面的代码中,我已经读取的CSV(有假数据,但你似乎已经掌握了该部分)
The max
function should handle that for you. In my below code I've already "read" the CSV (with fake data, but you seem to have a grasp on that portion)
data = [
["California", 123456],
["Idaho", 123],
["Utah", 2]
]
print max(data, key=lambda _: _[1])
这会产生 ['California',123456]
= lambda _:_ [1] 告诉函数使用每个记录的第二个值,在这种情况下为总体检查最大值。
The key=lambda _: _[1]
tells the function to use the second value of each record, the population in this case, to check the maximum.
将它们放在一起应该是:
Putting it all together should be something like:
def largestState():
INPUT = "statepopulations.csv"
COLUMN = 5
with open(INPUT, "rU") as csvFile:
data = csv.reader(csvFile)
next(data, None)
return max(data, key=lambda _: _[COLUMN])
这篇关于PYTHON:打开一个csv文件和找到一个列中的最大数目和名称assosciated与最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!