Convert text to matrix or numpy array and average the values

Viewed 54

Need to convert the following text to matrix and average it.

stat.txt //find the average of multiple occurrence
Node FC NL  SSD    FC NL   SSD FC NL SSD
   0  1  0    0 2500   0 67200  0  0   0
   1 16  0    0 25600  0 67200  0  0   0
   
Node FC NL  SSD    FC NL   SSD FC NL SSD
   0  1  0    0 35600  0 7200  0  0   0
   1  6  0    0 35600  0 7200  0  0   0

FC NL SSD are all values for NODE0 and NODE1. These values needs to be added and averaged out. Since the text has 2 occurance of the block. I need to add and average and display in the same format as: (but with average valves)

Result should be something like this:-

Node FC NL  SSD    FC NL   SSD FC NL SSD
   0  ## Average values corresponding to NODE0 ##
   1 ## Average values corresponding to NODE1 ##

I try to open the text and format:-

with open('stat.txt', 'r') as f:
    contents = f.read().split()

This gives me a list:-

 ['Node', 'FC', 'NL', 'SSD', 'FC', 'NL', 'SSD', 'FC', 'NL', 'SSD', '0', '1', '0', '0', '25600', .....

array = np.array(contents)
#print(array)
shape = (10, 6)
res = np.shape(array)
print(res)

With the above code i am trying to format it as a Matrix to add and average alternate rows. BUT not able to get the right format. ANY better way? Thanks!

1 Answers

Create a list of lists by:

  • make an empty list
  • iterate over the lines of the file
  • if a line starts with 'Node' skip it
  • if not, split the line and convert the items in the resultant list to numbers
    • append this list to the list you created at the beginning
  • when the file iteration stops, feed the list of lists to numpy.array.
Related