i'm super new to coding and trying to change a boolean set in a pandas df from True to False. I want to select a certain row, based on a name. My df, df_contacts looks like this:
name gender relationship category access timestamp proof
0 Emma female ex-girlfriend True 1653939064.769388 1
1 Amber female ex-girlfriend True 1653939064.769388 1
2 Mark male business False 1653939064.769388 1
3 Claire female ex-girlfriend True 1653939064.769388 1
4 Sara female co-worker False 1653939064.769388 1
5 Marcus male friend False 1653939064.769388 1
6 George male soccer-coach False 1653939064.769388 1
I want to change the value True, behind Emma's name, into False. How can i write this function based on user_input, and not on index?
I am stuck on this:
code
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
if block == 'yes':
df_contacts.loc[df_contacts["access"] == True, False]
print(df_contacts)
switch_access(name)
CodePudding user response:
This will change it using numpy
import numpy as np
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
if block.lower() == 'yes':
condition_list = [df_contacts['category'] == True, df_contacts['category'] == False]
choice_list = [False, True]
df_contacts['category'] = np.where(df_contacts['name'] == name, np.select(condition_list, choice_list, df_contacts['category']), df_contacts['category'])
return df_contacts
df = switch_access('Emma')
df
I also altered your code a little to make it slightly more fault tolerant
CodePudding user response:
You can use:
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access (name):
if block == 'yes':
df_contacts.loc[df_contacts['name'] == name, 'access'] = False
print(df_contacts)
switch_access('Emma')
Output:
name gender relationship category access timestamp proof
0 Emma female ex-girlfriend False 1.653939e 09 1 # True to False
1 Amber female ex-girlfriend True 1.653939e 09 1
2 Mark male business False 1.653939e 09 1
3 Claire female ex-girlfriend True 1.653939e 09 1
4 Sara female co-worker False 1.653939e 09 1
5 Marcus male friend False 1.653939e 09 1
6 George male soccer-coach False 1.653939e 09 1
CodePudding user response:
If you want to read the name along with changing the boolean value, you can use this code...
name = input("Enter name of contact: ")
block = str(input('Confirm restricting this contact from seeing your photos? '))
def switch_access(name, block):
if block.lower() == 'yes':
if df_contacts.loc[df_contacts["name"] == name]['access'][0] == True:
df_contacts.loc[df_contacts["name"] == name, 'access'] = False
print(df_contacts.loc[df_contacts["name"] == name])
switch_access(name, block)
Output
Enter name of contact: Emma
Confirm restricting this contact from seeing your photos? Yes
name gender relationship_category access timestamp proof
0 Emma female ex-girlfriend False 1.653939e 09 1