Issue
I want to get the uid using name for eg: someFunctionToFindUidOfName('Akt') //should return uid = 0, but don't know how to get that i am new to dataFrames please explain the answer
I also want to checkif dataFrame has username and password if it has it will print "user found!"
please answer in 1 and 2 differently and please explain as much as u can in simple terms π₯Ίπ’π’
Solution
I think this is what you are looking for:
First to construct a DataFrame with the same format as yours:
import pandas as pd
d = {'name': ['name1', 'name2', 'name3'], 'password' : ['1234', '4567', abcd']}
df = pd.DataFrame.from_dict(d)
df.index.name = 'UID'
print(df)
which will give the output below. Notice that the first column is different - it is the index as in your data.
name password
UID
0 name1 1234
1 name2 4567
2 name3 abcd
Then code to get an uid and test it.
def get_uid(want_name):
result = df[df['name'] == want_name]
if result.empty:
return('No such user from get_uid ' + want_name)
else:
return (want_name + ' uid is ' + str(result.index.item()))
print(get_uid('name2'))
print(get_uid('name4'))
How this works is that to select the row with the query name and if it exists get the index item (that is under the UID heading). As it is a number it is converted to a string. So it gives:
name2 uid is 1
No such user from get_uid name4
Next use a similar approach to check for a user and get the password:
def check_user(want_name):
result = df[df['name'] == want_name]
if(result.empty):
return ('No such user from check_user ' + want_name)
else:
return (want_name +' User found with password ' + result['password'].item())
print(check_user('name2'))
print(check_user('name4'))
which gives results:
name2 User found with password 4567
No such user from check_user name4
The part that might need explaining is result = df[df['name'] == want_name]
. What this does is select from the DataFrame that part where the expression inside df[ ] is True. Then the result can be used to give the part of the data of interest. To check both user and password then:
def check_user_pass(want_name, try_pass):
result = df[df["name"] == want_name]
if result.empty:
return 'No such user'
else:
real_pass = result["password"].item()
if real_pass != try_pass:
return 'No such user *'
return 'User found'
print(check_user_pass('name1', '1234'))
Answered By - user19077881
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.