Search code examples
pythonarraysnumpycoordinatesexport-to-csv

Printing Coordinates to a csv File with Data


I need to extract coordinates with associated data to a .csv file.

I have a 4x4 matrix written as a list (network1) as well as corresponding values for each index (q_val). My goal is to identify the coordinates where a 1 occurs within network1, and export these coordinates along with the corresponding q_val to a .csv file.

Please see the current code below:

network1 = [0,1,0,0,0,0,1,0,0,0,1,1,0,0,1,1]
q_val = [50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800]

data = np.array(network1)
shape = (4,4)
network2 = data.reshape(shape)
print(network2)

coordinates = np.where(network2 == 1)
print(coordinates)

listOfCoordinates= list(zip(coordinates[0], coordinates[1]))

for coords in listOfCoordinates:      
    print(coords)

My Python output from this process looks correct and is as follows:

[[0 1 0 0]
 [0 0 1 0]
 [0 0 1 1]
 [0 0 1 1]]

(array([0, 1, 2, 2, 3, 3], dtype=int64), array([1, 2, 2, 3, 2, 3], dtype=int64))

(0, 1)
(1, 2)
(2, 2)
(2, 3)
(3, 2)
(3, 3)

It would be great to get some assistance to complete the following additional steps:

  1. Shift the indices by +1 [i.e. the results should be (1,2), (2,3), (3,3), (3,4), (4,3), (4,4)].
  2. Print these to a .csv file without the brackets and commas, delimited by spaces only. This should look like the photo below.
  3. Ideally, I would also like it to print with the q_val in the header and the ; below the results.

Ideal output

I greatly appreciate any help - I'm sure there are more efficient methods of completing this process as well, so I am more than happy to take on board any suggestions!


Solution

  • This should satisfy your requirements:

    import numpy as np
    import pandas as pd
    
    network1 = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1]
    q_val = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800]
    
    network1_matrix = np.array(network1).reshape(4, 4)
    q_val_matrix = np.array(q_val).reshape(4, 4)
    
    
    coordinates = np.transpose(np.where(network1_matrix == 1))
    
    filtered_values = [q_val_matrix[tuple(coordinate)] for coordinate in coordinates]
    
    # Create the DataFrame and add 1 to each index
    result_df = pd.DataFrame({'1': coordinates[:, 0] + 1, '2': coordinates[:, 1] + 1, '3': filtered_values})
    # Add ';' in the end of the DataFrame
    result_df = result_df.append({'1': ';', '2': '', '3': ''}, ignore_index=True)
    # Add 'q_val' as header
    result_df.columns = ['q_val', '', '']
    # Export the DataFrame as csv file
    result_df.to_csv('result.csv', sep=' ', index=False)