我有一个列表,例如fruitList = [Apple, Mango, Banana]
。我有一个csv文件,其中包含一堆列,其中包括列表中的列。
例如:
Orange Apple Strawberry Banana
1 12 5 11
2 3 10 9
如何获取一列csv,例如“香蕉”作为列表?
到目前为止我尝试过的事情:
data_file = open('fruit_data.csv')
data_reader = csv.reader(data_file, delimiter=",")
header = data_reader.next()
my_list = []
for field in header:
for fruits in fruitList:
if(fruits==field):
mylist = header[fruits]
我知道代码的最后一行是错误的。我想知道如何使用字符串变量作为列表索引在csv中获取信息。
谢谢!
答案 0 :(得分:1)
您可以执行以下步骤:
import csv
list= [tuple(row) for row in csv.reader(open(filename, 'rU'))]
以上代码将以以下形式获取数据:
list = [('Orange', 'Apple', 'Strawberry', 'Banana'), (1, 12, 5, 11), (2, 3, 10, 9)]
您可以执行的下一步是:
new_list = [x[3] for x in list]
输出:
new_list = ['Banana', 11, 9]
我希望这可以解决您的问题,如果不能,请告诉我。我很乐意提供帮助!
和平///
Parthik Bhandari
答案 1 :(得分:1)
例如。
from collections import defaultdict
import csv
the_data = defaultdict(list)
with open("fruit_data.csv", "r") as fd:
reader = csv.DictReader(fd)
for row in reader:
for fruit, number in row.items():
the_data[fruit].append(number)
for fruit, the_list in the_data.items():
print fruit, the_list
O / P:
Orange ['1', '2']
Strawberry [' 5', ' 10']
Apple [' 12', ' 3']
Banana [' 11', ' 9']
答案 2 :(得分:0)
我使用熊猫的tolist()命令所做的贡献:
import pandas as pd
data_file = pd.read_csv('fruit_data.csv')
# Creating data containers
fruitList = ['Apple', 'Mango', 'Banana']
names_columns = []
list_names = []
# Extracting the columns names from the imported cvs file
columns = list(data_file)
for i in columns:
names_columns.append(i)
# Getting the columns of the csv file as lists when the criteria is meet
for fruit in fruitList:
for name in names_columns:
if name==fruit:
list_names.append(name)
# Printing the desired lists
for name in list_names:
print(name, data_file[name].tolist())
Apple [12, 3]
Banana [11, 9]