import numpy as np
value_to_replace = "whatever"
# This is saying if B == value_to_replace, set column B to A, else just leave as B
# result = np.where((conditional), value if true, value if false)
df["Column B"] = np.where((df["Column B"] == value_to_replace), df["Column A"], df["Column B"])
# extension of above where if B == value_to_replace, set B to first 2 characters of B + all of A, else leave as B:
df["Column B"] = np.where((df["Column B"] == value_to_replace), df["Column B"].str[:2] +df["Column A"], df["Column B"])
如果希望替换应用于每一行,则更简单:
# this just sets column B to column A
df["Column B"] = df["Column A"]
# this sets column B to the first 2 characters of column B + all of column A
df["Column B"] = df["Column B"].str[:2] + df["Column A"]
只要用替换超链接所需的任何字符串操作来替换first 2 characters of B + all of A位即可
如果只想替换一个特定的列B值,请尝试使用
np.where
:如果希望替换应用于每一行,则更简单:
只要用替换超链接所需的任何字符串操作来替换
first 2 characters of B + all of A
位即可相关问题 更多 >
编程相关推荐