从CSV文件中获取数据并将其转换为variab

2024-05-15 17:32:00 发布

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

我有一个csv文件,它的格式是Steward、Department、Location、Subnet、Appliance。第一行并不重要,因为它只包含标题。我想在for循环中将每一行设置为一个变量进行数据处理,所需的格式基于以下CSV数据:

Subnet,Location,Department
10.10.240.0/26,bldg1,finance
10.10.240.128/25,bldg2,IT
10.10240.128/25,bldg3,Admin
10.10.244.96/27,bldg4, foo



title =department + ' - ' + location + ' - ' + subnet

Tags: 文件csv数据标题for格式location中将
1条回答
网友
1楼 · 发布于 2024-05-15 17:32:00

您可以使用^{}轻松地解压csv文件

>>> import numpy as np
>>> Stewards, Departments, Locations, Subnets, Appliances = np.genfromtxt("a.csv", delimiter=',', dtype='string', unpack=True)

这将创建5个名为Stewards, Departments... etc的数组,将csv文件中的每个项包含在各自的列中。如果您想跳过头文件,可以使用np.genfromtxt( ... , skip_header=1)跳过文件中的第一行。你知道吗

不要试图将这些数据存储在一堆单独的变量中——那将是更多的工作和糟糕的做法。而是创建一个字典。我只是根据文件中数据的顺序来设置键。你可以用你想要的任何东西作为你的钥匙。你知道吗

>>> import numpy as np
>>> Stewards, Departments, Locations, Subnets, Appliances = np.genfromtxt("a.csv", delimiter=',', dtype='string', unpack=True)
>>> alist = zip(Stewards, Departments, Locations, Subnets, Appliances)
>>> adict = {i: alist[i] for i in range(len(alist))}
>>> adict ## I just used some letters to fill in the csv file, but as long as you 
          ## didn't use commas in any of the inputs you'll be fine
{0: ('Steward', 'Department', 'Location', 'Subnet', 'Appliance'), 1: ('a', 'b', 'c', 'd', 'e'), 2: ('g', 'h', 'i', 'j', 'k'), 3: ('m', 'n', 'o', 'p', 'q')}

它使用^{}内置和dictionary comprehensions。你知道吗

如果需要从中提取数据并创建字符串,只需使用for循环即可。你知道吗

string_list = []
for i in range(len(adict)):
    string_list.append( ... )

相关问题 更多 >