正在尝试使用pd.df列值替换同一行中的字符串值,分隔列

2024-09-04 19:12:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用.iat,但这是一个静态值。我有大约75行和两列,我想用列“a”中的域替换列“B”中的超链接。我认为.iat是最好的方法,但我无法计算(当前行,1)的动态值

让我再解释一下,因为下面的答案对于我的问题来说有点过于简单化了

我想用A列中每个对应行的不同唯一值替换B列中的标记{URL}

df['Column A'] = ('xyz.com', 'abc.com')
df['Column B'] = https://thisone.com/xxx/x?{URL}/xxx/xxx

Tags: 方法答案https标记comurldf静态
1条回答
网友
1楼 · 发布于 2024-09-04 19:12:54

如果只想替换一个特定的列B值,请尝试使用np.where

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位即可

相关问题 更多 >