如何用python从csv文件格式读取数据

2024-09-27 02:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读取CSV文件。你知道吗

在第一列的.CSV文件中,我有一个不同的变量(例如,N11,N12,N21,N22,…,N38)。在第3列中,我对每个变量有不同的值。第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])

谢谢你。你知道吗


Tags: 文件csv数据csvfile代码示例顺序row
3条回答

我个人建议你使用熊猫模块。你知道吗

您可以轻松地创建数据结构和管理数据库。它是一个开源库,为Python编程语言提供高性能、易于使用的数据结构和数据分析工具。你知道吗

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

对于这个特殊的问题,你可以:

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

这将创建一个名为“dataframe”的定制数据结构(显然,选择完全取决于您),它的数据可以轻松有效地进行操作

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最大值=15 N11最小值=11

工作样品

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

假设

  • 如果第一列只有一个值,它将被设置为max和min

代码,注释和解释

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']}

相关问题 更多 >

    热门问题