我對編碼和嘗試將 pandas 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)
uj5u.com熱心網友回復:
這將使用 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
我還稍微修改了您的代碼,使其更容錯
uj5u.com熱心網友回復:
您可以使用:
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
uj5u.com熱心網友回復:
如果您想在更改布林值的同時讀取名稱,可以使用此代碼...
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483172.html
