I'm trying to replace the values in one column of a data frame with other .
enter code here
"data = {'name':['Tom', 'nick', 'krish'], 'value':[20, 21, 19]}
df = pd.DataFrame(data)
s= "*** is good boy and he got ###"
df['sentence']=s
i want to replace the value of *** with name column values and ### with value column values"
Expected output is : "Tom is good boy and he got 20" "nick is good boy and he got 21" ""krish is good boy and he got 19"
CodePudding user response:
You can use apply function and take both the values from the columns and write a custom function f.
def f(n,v):
return n " is good boy and he got " v
df['sentence'] = df.apply(lambda x: f(x['name'], x['value']), axis=1)
let me know if this solution works. do upvote :) if you find it helpful
CodePudding user response:
One possible way would be to use list comprehensions in pandas dataframes. Because we want to iterate over two columns we need to zip them before iterating. We then use an f string(formatted string) to use the variables inside of the string. We assign this list comprehension to the new column like that:
df = pd.DataFrame(data)
df["sentence"] = [f"{name} is good boy and got {value} points" for name, value in zip(df["name"],df["value"])]
