如何使用python

时间:2019-12-21 05:02:29

标签: python python-3.x csv

我想读取CSV文件。

在.CSV文件的第一列中,我有一个不同的变量(例如N11,N12,N21,N22,...,N38)。在第三列中,我对每个变量都有不同的值。第3列中的值是随机放置的(不是任何顺序)。

我想针对每个变量(N11,N12 ...等)获取最小值和最大值。 例如,示例数据中给出了N11最小值= 1573231694和N11最大值= 1573231738。

在.csv文件中,每个变量包含数千个元组,如下所示:

enter image description here

我正在尝试以下代码。 有人可以帮助我根据上述要求修改以下代码吗?

import csv
with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row[2])

谢谢。

3 个答案:

答案 0 :(得分:0)

工作样本

N11,12,123,123,0
N21,12,133,123,0
N12,12,143,123,0
N32,12,125,123,0
N11,12,121,123,0
N12,12,121,123,0
N11,12,122,123,0
N21,12,127,123,0
N32,12,183,123,0
N14,12,193,123,0

假设

  • 如果第一列只有一个值,它将同时设置为最大值和最小值

代码,带有解释注释

import csv

# Collect the pairs in a dict of lists where the first value is the minimum 
# and the second the max

min_max = dict() 

with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    for row in readCSV:

        # Check if the value already exists in the dict
        row_val = min_max.get(row[0]) 

        if row_val is not None:
            row_min = min_max[row[0]][0] # Get the min
            row_max = min_max[row[0]][1] # Get the max

            # Check against current value
            min_max[row[0]][0] = min(row[2], row_min) 
            min_max[row[0]][1] = max(row[2], row_max)   
        else:
            # If it doesn't exist update the dict
            min_max[row[0]] = [row[2], row[2]]

    print(min_max)

输出

{'N11': ['121', '123'], 'N21': ['127', '133'], 'N12': ['121', '143'], 'N32': ['125', '183'], 'N14': ['193', '193']}

答案 1 :(得分:0)

我个人建议您使用pandas模块。

您可以轻松创建数据结构并轻松管理数据库。它是一个开放源代码库,为Python编程语言提供了高性能,易于使用的数据结构和数据分析工具。

在此处查看有关使用熊猫的文档: https://pandas.pydata.org/pandas-docs/stable/

对于这个特殊的问题,您可以这样做:

import pandas as pd
dataframe = pd.read_csv("*File Path Here*")

这将创建一个自定义的熊猫数据结构,名为“ dataframe”(显然完全由您决定),其数据可以轻松有效地操作

答案 2 :(得分:0)

df=pd.DataFrame({'col1':['N11','N12','N11','N14'],'col2':[1, 3, 5, 7],'col3':[11,13, 15, 17]})
print("N11 max=",df['col3'][df['col1']=='N11'].max())
print("N11 Min=",df['col3'][df['col1']=='N11'].min())

输出:N11 max = 15 N11 Min = 11