我对编码非常陌生,并试图将熊猫df中的布尔集从True更改为False。我想根据名称选择某一行。我的df, df_contacts看起来像这样:
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
我想把Emma名字后面的True值改为False。我怎么写这个函数基于user_input,而不是索引?
我被困在这个: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)
这将使用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
我还稍微改变了你的代码,使它更容错
您可以使用:
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')
输出:
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
如果您希望读取名称并更改布尔值,可以使用以下代码…
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)
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