[英]How do I read specific rows AND columns in CSV file while printing values within a certain range
Hi I am having some problems looking at specific rows and columns in an csv file. 嗨,我在查看csv文件中的特定行和列时遇到一些问题。
My current goal is look 3 different columns out the several that are there. 我当前的目标是在其中的三个不同的列中查找。 And on top of that, I want to look at the data values (ex. 0.26) and sort through the ones that are betweeen 0.21 and 0.31 in a specific column. 最重要的是,我想查看数据值(例如0.26),并在特定列中对0.21和0.31之间的数据进行排序。 My issue is that I dont know how to do both of those at the same time. 我的问题是我不知道如何同时做这两个。 I keep getting errors that tell me i cant use '<=' with float and str. 我不断收到错误消息,告诉我我不能在float和str中使用'<='。
Heres my code: 这是我的代码:
import csv
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
with open('C:\\Users\\AdamStoer\\Documents\\practicedata.csv') as f:
reader = csv.DictReader(f,delimiter=',') # read rows into a dictionary format
for row in reader:
for columns['pitch'] in row:
for v in columns['pitch']:
p=float(v)
if p <= 0.5:
columns['pitch'].append(v)
print(columns['pitch'])
This code was working before for the last part 该代码在最后一部分之前是有效的
for row in reader: # read a row as {column1: value1, column2: value2,...}
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# based on column name k
print(columns['pitch'])
Looks like you're confusing a couple things. 看起来您在混淆两件事。 If you know the specific column you want (pitch) you do not have to loop over all the columns in each row. 如果知道想要的特定列(间距),则不必遍历每一行中的所有列。 You can access it directly like so: 您可以像这样直接访问它:
for row in reader:
p = float(row['pitch'])
if p <= 0.5:
print p
It's hard for me to tell what output you want, but here's an example that looks at just the pitch in each row and if it is a match appends all the target values for that row to the columns dictionary. 我很难说出您想要什么输出,但是这里有一个示例,仅查看每行的音高,如果匹配,则将该行的所有目标值附加到column字典中。
targets = ('pitch', 'roll', 'yaw')
columns = defaultdict(list)
for row in reader:
p = float(row['pitch'])
if p >= 0.21 and p <= 0.31:
for target in targets:
column[target].append(row[target])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.