【问题标题】:Getting a column into an array from excel in python从python中的excel将一列放入数组
【发布时间】:2014-12-31 04:01:25
【问题描述】:

作为我正在做的项目的一部分,我需要创建一个排名表,并且为了按积分对其进行排序,我需要从 excel 访问积分列并对其进行排序。到目前为止,我为此编写的代码是:

output = []
x = open("table.csv", "rU")
for line in x:
    cells = line.split(",")
    output.append((cells[7]))
print output

Points 是所有列中的最后一列,总共 7 个。输出是:

['Points\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n', '0\n']

有没有办法只获取数字,然后在不使用 pandas 的情况下订购它们?

谢谢

【问题讨论】:

    标签: python arrays excel csv


    【解决方案1】:

    你应该看看CSV module,它会帮助你做到这一点。

    查看您已有的代码,您想跳过列标题并在“单元格”上调用strip() 以删除新行。输出前,对输出列表进行排序:

    output = []
    with open("table.csv", "rU") as x:
        next(x)    # skip header row
        for line in x:
            cells = line.split(",")
            output.append((cells[7].strip()))
    output.sort()
    print output
    

    您的代码可以简化为:

    with open("table.csv", "rU") as f:
        output = sorted([line.split(',')[7].strip() for line in f][1:])
    

    或者您可以使用 CSV 模块:

    import csv
    
    with open("table.csv", "rU") as f:
        reader = csv.reader(f)
        next(reader)
        output = sorted(row[7] for row in reader)
    

    【讨论】:

    • @RobertAvill :没问题。如果您的问题得到解决,请考虑投票并接受此答案。
    猜你喜欢
    • 2014-11-12
    • 1970-01-01
    • 2020-12-28
    • 2020-10-03
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多