I want to read the csv file with numpy and create a dictionary using a tuple (which contains data from the csv file).

Asked 2 years ago, Updated 2 years ago, 96 views

[Introduction]
I am trying to create a dictionary using tuple in python, but an error occurred and I cannot create it.
I'm sorry, but I'd appreciate it if you could tell me how to correct the error.
Thank you for your cooperation.

】What I want to realize したい
I am currently studying graph theory, and in the process, I am making the following dictionary.

dicts={(i_1,j_1):length_1,(i_2,j_2):length_2,...,(i_10,j_10):length_10}

i—Leaving node
j —Arriving node
length —The distance between i and j

Specifically, we aim to create the following dictionary by substituting the attached test.csv number.

dicts={(2,20):100, (4,18):200,...,(20,2):1000}

試What I tried and what I'm experiencing (error message) <
If you run the appropriate source code, you will get an error similar to the following:
I looked up the error online, but I couldn't understand it.
There seems to be a problem with numpy, but I really want to use numpy, so I haven't tried other methods of loading data (pandas, etc.).

TypeError:unhashable type: 'numpy.ndarray'

[Applicable source code]
With the aim of creating a dictionary, we have organized the following programs:

import numpy as np

data=np.loadtxt("test.csv",      
                  delimiter=",",   
                  skiprows = 1,      
                  usecols=(1,2,3) 
                 )

keys=[(data[i:i+1,0:1], data[i:i+1,1:2]) for i in range(0,10)]
values = [ data [ i:i + 1, 2:3 ] for i in range (0,10) ]

dicts = {}
for i in keys:
    for x in values:
       dicts[i] = x
       print(dicts)

test.csv is as follows:

fidij length
1   2   20  100
2   4   18  200
3   6   16  300
4   8   14  400
5   10  12  500
6   12  10  600
7   14  8   700
8   16  6   800
9   18  4   900
10  20  2   1000

python numpy csv

2022-09-29 21:40

3 Answers

You can do it like this

dct=dict(zip(map(tuple,data[:,:2],data[:,2])))
display(dct)

It looks like this when you break it down (corrected by comment: 1:3=>:2, 3=>2)

k=data[:,:2]#keys:numpy.ndarray
v=data[:,2]#values:array like
k_t=map(tuple,k)
dict(zip(k_t,v))


2022-09-29 21:40

The numpy.loadtxt—NumPy v1.21 Manual has a keyword called unpack.

unpack:bool, optional

If True, the returned array is translated, so that arguments may be unpacked using x, y,z=loadtxt(...).When used with a structured data-type, arrays are returned for each field.Default is False.

You can also use this feature to write as follows:

import numpy as np

i,j,length=np.loadtxt(
  'test.csv', delimiter=',', skiprows=1,
  usecols=(1,2,3), dtype=int, unpack=True)

dic = dict(zip(zip(i,j),length))
print(dic)

#=>
{(2, 20): 100, (4, 18): 200, (6, 16): 300, (8, 14): 400, (10, 12): 500, (12, 10): 600, (14, 8): 700, (16, 6): 800, (18, 4): 900, (20, 2): 1000}

I understand that using pandas is easy to convert, so I will introduce it to you for your reference.

import pandas as pd
from print import print

df = pd.read_csv('test.csv')
dfx = df.set_index(['i', 'j']) ['length'].to_dict()

print(dfx)

# =>
{(2, 20): 100,
 (4, 18): 200,
 (6, 16): 300,
 (8, 14): 400,
 (10, 12): 500,
 (12, 10): 600,
 (14, 8): 700,
 (16, 6): 800,
 (18, 4): 900,
 (20, 2): 1000}


2022-09-29 21:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.