我正在尝试为数据创建基线。我需要从每个列表中获取每列的平均值,并且有十个列表。每个列表有大约50个元素。从每列中取出均值可以得到道路上那个点的平均值,所以我需要注意不要取列表的平均值。我可以通过在文件名循环中索引来单独获取每一列,但效率非常低。然后我会使用MatplotLib绘制数据图,但这部分应该很简单。这是我到目前为止的代码:
def graphWriterIRI():
n = 0
for filename in os.listdir(os.getcwd()):
# Initialize a new set of lists for each file
startList = []
endList = []
iriRList = []
iriLList = []
# Load the file
if re.search('BASELINE',filename):
with open(filename, 'rU') as file:
for row in csv.DictReader(file):
try:
startList.append(float(row['Start-Mi']))
endList.append(float(row[' End-Mi']))
except:
startList.append(float(row['Start-MP']))
endList.append(float(row[' End-MP']))
try:
iriRList.append(float(row[' IRI R e']))
iriLList.append(float(row['IRI LWP ']))
except:
iriRList.append(float(row[' IRI RWP']))
iriLList.append(float(row['IRI LWP ']))
print iriRList[0] # prints column[0] of the list but I need this for 50 rows and two lists.
以下是我在代码中引入的一些数据:
Start-Mi End-Mi IRI LWP IRI R e
194.449 194.549 80.3 87.4
194.549 194.649 85.3 91.1
194.649 194.749 87.4 95.6
194.749 194.849 83.6 72.5
194.849 194.949 73.7 81
194.949 195.049 85.2 87.2
195.049 195.149 106.3 111.5
195.149 195.249 84.2 92.4
195.249 195.349 95.5 95.5
195.349 195.449 60.1 67.2
195.449 195.549 56.6 51.3
195.549 195.649 80.6 74.4
195.649 195.749 73.7 69.9
195.749 195.849 49.6 48.1
195.849 195.949 48.1 50.2
195.949 196.049 53.3 45.2
196.049 196.149 55.8 45.8
196.149 196.249 46.7 48.1
我特别想要做的是获取每个文件的iriRList和iriLList中列的平均值,每个文件都是一个列表。
答案 0 :(得分:2)
内置函数Database relation, and view.将转置序列序列。您可以使用它为每列创建元组。我不确定您是如何构建所有数据的,但这是个主意:
>>> one = [1,2,3,4]
>>> two = [2,3,4,5]
>>> three = [3,4,5,6]
>>> for column in zip(one, two, three):
print(column, sum(column), sum(column) / 3.0)
((1, 2, 3), 6, 2.0)
((2, 3, 4), 9, 3.0)
((3, 4, 5), 12, 4.0)
((4, 5, 6), 15, 5.0)
>>>
如果您累积每个文件中的列表:
def graphWriterIRI():
n = 0
iRlists = []
for filename in os.listdir(os.getcwd()):
...
...
print iriRList[0]
iRlists.append(iriRList)
您可以这样使用它:
>>> for column in zip(*iRlists):
print(column, sum(column), sum(column) / float(len(iRlists)))
((1, 2, 3), 6, 2.0)
((2, 3, 4), 9, 3.0)
((3, 4, 5), 12, 4.0)
((4, 5, 6), 15, 5.0)
>>>