How to use user input to select row column and ret

2019-07-27 07:09发布

问题:

I have a pandas dataframe constructed from a csv file.

I ask the user for two values, separated by a space.

I then attempt to do a pandas.loc[,] to return that cell value.

How do I match their input to my row columns and return just the raw value of that cell? Impossible in Python? My program works well so far in determining which csv table to look up and how to assign the input to variables. It's the actual passing to the chart lookup that doesn't work. Here is some sample code.

import pandas as pd

A_read = pd.read_csv('My.csv')
A1 = pd.DataFrame(A_read)
A = A1.set_index("Years")

separator = ' '
user_input = raw_input("Enter two values: ").split(separator)
rank = user_input[0]
Years = int(user_input[1])

pay = A.loc[ , ] #problem area

I process the Years input into an int and then input it to a sorting table giving it the value of 'Over 0' or 'Over 5' etc. This string matches the terms in my index like in the example table here. Rank is input as string and no changes are made.

Years    E-9        E-8
Over 0   40         80
Over 2   30         20

I only wrote a lot to be clear! Just looking for any solutions that takes inputs and matches them to rows/columns to return a cell.

回答1:

Let A be

A = pd.DataFrame(
    np.random.randint(10, size=(10, 10)),
    list('abcdefghij'), list('ABCDEFGHIJ'))

   A  B  C  D  E  F  G  H  I  J
a  1  8  0  3  5  7  7  2  7  1
b  7  7  6  6  1  1  3  4  3  9
c  8  4  9  4  6  7  2  8  1  5
d  1  0  2  4  0  5  1  7  9  6
e  9  0  3  2  3  6  6  9  5  0
f  5  6  2  0  7  9  2  0  8  0
g  7  7  0  5  2  6  1  9  0  1
h  5  8  0  7  4  0  7  3  1  7
i  9  9  6  2  7  7  3  5  0  9
j  3  1  8  0  1  8  9  7  5  9

Grab user input... Notice the assignment to i and j. You had a split but were only grabbing the first value in the split

i, j = input('>>>  ').split()
>>>  i C

A.loc[i, j]

6