目標是根據其他條件覆寫一個值,但如果一個值是某個字串,則不要覆寫它。我剛剛開始撰寫代碼,不知道如何解決這個問題,或者我的方法是否最有效。
這是我目前正在嘗試的:
for cell_value in df['col1']:
if cell_value == 'a':
continue
'''
with this part I'm trying to get the code not to alter these existing values
'''
for cell_value in df['col1']:
if cell_value in df.loc((df['col2'] == 'red') & ((df['number']) == 0) &
((df['col_4'].str.contains("color")))):
cell_value = 'This is red'
'''
With this part I'm attempting for the code to change the cell_value in 'col1' to
'This is red' while not changing those values in 'col1' that equal 'a'
'''
我什至不確定我是否走在正確的軌道上,或者是否可以使用我不完全理解的 mask() 來完成。
我得到的當前錯誤是:
TypeError:不可散列的型別:“系列”
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
我認為你不需要回圈。可以用np.where()來完成。如果我正確理解了這個問題,這將起作用。
import numpy as np
df['col1']=np.where(((df['col1']!='a') & (df['col2'] == 'red') & ((df['number']) == 0) & ((df['col_4'].str.contains("color")))),'This is red',df['col1'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/519750.html
上一篇:如何在PythonPandas中將多行組合成一行而不使用groupby?
下一篇:Groupby均值不顯示所有資料
