How can we access the value of a matrix in Python, if I pass its column and row name as input in Python code.
For Example – If I input A
as column and B
as row, then from the matrix table, I should get its A and B map value.
So far I tried this code, but I was unable to figure out how to get its value:
JavaScript
x
16
16
1
import numpy as np
2
import pandas as pd
3
4
input1= 'B'
5
input2= 'B'
6
7
numpyArray = np.array([[5, 4, 3, 3, 2, 2],
8
[4, 3, 2, 3, 2, 1],
9
[3, 3, 1, 2, 1, 1],
10
[2, 2, 1, 1, 1, 1]])
11
12
panda_df = pd.DataFrame(data=numpyArray, index=["A", "B", "C", "D"],
13
columns=["A", "B", "C", "D", "E", "F"])
14
15
print(panda_df)
16
Also, is it possible to achieve this solution in python 2.7?
Advertisement
Answer
Taking advantage of your created dataframe, just select according to the inputs:
JavaScript
1
2
1
panda_df[input1][input2]
2
But you can avoid the dataframe creation by creating a translation from letters to indexes using ord
(assuming the inputs will always be capitalized letters, starting from A
):
JavaScript
1
6
1
def letter_to_i(letter):
2
"""
3
A -> 0, B -> 1,
4
"""
5
return ord(letter) - ord('A')
6
And now index the array directly:
JavaScript
1
2
1
numpyArray[letter_to_i(input1)][letter_to_i(input2)]
2