relatively new to using Python and the dict structure. I have imported a CSV file from online and turned it to a dictionary. I use the first row as the Key, and then any other subsequent rows are used as the value.
becomes
Date {0: '04-Nov-22', 1: '05-Nov-22'}
USD {0: 0.9872, 1: 2.9872}
JPY {0: 145.19, 1: 11115.19}
I am curious as to why when I do for example:
print('0.9872' in df.values())
that returns me a false, since its clearly there. This is probably fairly trivial, but in the end what I want to do is:
The user inputs a date in the above format, and this date will determine which values will be used later on in my program. So if a user enters 04-Nov-22, I need to record the fact that this is the 0th value in the key:value pair, so from now on only use other 0th values, i.e 0.9872 and 145.19.
Anyway sorry for rambling, so all I want to get out of this is:
data_input = input("Enter the data in DD-MM-YY format please: ")
print(data_input in df.values())
-< for this to not be False
CodePudding user response:
For a number (int, float) you would not need to put '' around it. '' or "" is declaring a string, which means the compiler thinks you're searching for a string when in reality you're searching for a number. Take the image provided below as an example: Example
Here, we have a list of numeric values (ints/floats) and you can see that when the compiler went over the if statement, which contained the number surrounded by '', it was marked as false, but when it went over the if statement which contained the plain number, it was marked as true.
So, in this case, you'd want to change your code to this:
print(0.9872 in df.values())
As for the input portion, by default input() will return the input as a string instead of a variable, so again you're telling the compiler to search for the user input as a STRING rather than a NUMBER. This can be easily solved by converting the string to an integer, like this:
print(int(data_input) in df.values())
This will work assuming the user inputs a proper numeric value.
CodePudding user response:
To produce the table in the format you present you could use:
import pandas as pd
df = pd.DataFrame.from_dict({'Date': ['04-Nov-22', '05-Nov-22'], 'USD': [0.9872, 2.9872], 'JPY': [145.19, 11115.19]})
df = df.set_index('Date')
and then if you use:
print(df)
print(0.9872 in df.values)
print('04-Nov-22' in df.index)
you would get the output:
USD JPY
Date
04-Nov-22 0.9872 145.19
05-Nov-22 2.9872 11115.19
True
True
If you miss out the set_index line then Pandas would provide a numerical index and you would find '04-Nov_22' in df.values. You could try this.