簡體   English   中英

使用if語句在python中替換字符串

[英]String replace in python using if statement

嘗試根據列值替換字符串,得到錯誤 ValueError: The truth value of a Series 不明確。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

if df['Target'] == 'U':
   df['Target'] = df['Action'] 

獲取錯誤值錯誤:系列的真值不明確。 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

只是我需要檢查字符串並在匹配時將其替換為另一個列值

使用np.where

前任:

import numpy as np

df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])

您可以使用pandas.DataFrame.loc

df.loc[df["Target"] == 'U', "Target"] = df["Action"]

您還可以使用pandas.DataFrame.where

df["Target"].where(df["Target"] != 'U', df["Action"], inplace = True)

請注意,在這種情況下,不滿足條件的細胞所取代,這就是為什么你必須使用!=而不是==

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM