我在通过从csv文件读取的if参数放置for循环后尝试创建数组。在下面的代码中,我打印结果。我想将它们存储在一个数组中,而不是打印结果。我该怎么做呢?
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
if float(line['Rel Volume']) > 2.5:
print(line['tckr'],line['Rel Volume'])
答案 0 :(得分:2)
试试这样:
arr = []
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
if float(line['Rel Volume']) > 2.5:
arr.append(line['tckr'],line['Rel Volume'])
答案 1 :(得分:0)
如果你想要一个嵌套的列表列表(每个内部列表包含两个元素),请执行以下操作:
my_list = []
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
if float(line['Rel Volume']) > 2.5:
my_list.append([line['tckr'],line['Rel Volume']])
如果您想要一个扁平(一维)列表,请执行以下操作:
my_list = []
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
if float(line['Rel Volume']) > 2.5:
my_list.extend([line['tckr'],line['Rel Volume']])
两个示例之间的唯一区别是,一个使用extend()
,另一个使用append()
。请注意,在每种情况下,我们通过在line['tckr'],line['Rel Volume']
周围加上方括号将单个列表传递给我们选择的任何方法。
答案 2 :(得分:0)
Pandas模块非常适合修改:
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 09 17:21:57 2018
@author: soyab
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%%
## Load as a Pandas Dataframe ; Select rows based on Column logic
new_df = pd.read_csv('_Stocks.csv')
df_over_two_five = new_df.loc[new_df['Rel Volume'] > 2.5].copy()
df_over_two_five
通过这样的问题发布您的数据是很好的。然后我可以确保捕捉到愚蠢的错误。
答案 3 :(得分:0)
您可以使用列表理解来执行此操作!我的下面的示例将使用一个名称元组,但您不必包含它,它不是必需的。
from collections import namedtuple
CSVLine = namedtuple('CSVLine', ['tckr', 'Rel_Volume'])
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
csvfilter = [ CSVLine(line['tckr'], line['Rel Volume']) for line in csv_reader if line['Rel Volume'] > 2.5]
使用namedtuple,您的数组数据将如下所示:
CSVLine(tckr='abcd', Rel_Volume=3.2), CSVLine(tckr='efgh', Rel_Volume=3.0), CSVLine(tckr='ijkl', Rel_Volume=4.2)
如果没有namedtuple,它将如下所示:
with open('_Stocks.csv') as csv_file:
csv_reader = csv.DictReader(csv_file)
csvfilter = [(line['tckr'], line['Rel Volume']) for line in csv_reader if line['Rel Volume'] > 2.5 ]
我在两个示例中都使用了元组,因为我假设您希望将每行中的数据配对在一起,以备日后使用。