В приведенной ниже таблице я хочу создать новый столбец или обновить столбец комментариев, который может заменить слово-заполнитель «NameTag» значением в столбце «Name» и слово «IDTag» значением в столбце «ID».
Я хочу, чтобы вывод был таким...
Я попробовал функцию замены pandas, но не получилось заменить слово именем столбца... ошибка ниже
ValueError: Series.replace не может использовать значение dict и не-None to_replace
Использование .apply и лямбда:
df["Comment"] = df.apply(lambda x: x["Comment"].replace("NameTag", x["Name"]), axis=1)
import pandas as pd
data = {'ID': ['A1', 'A2'], 'Name': ['Alex', 'Alice'], 'Comment': ['the name NameTag belonging to IDTag is a common name', 'Judging the NameTag of IDTag, I feel its a girl\'s name']}
df = pd.DataFrame(data)
df['Personalized'] = df.Comment.replace(['NameTag'] * len(df), df.Name, regex=True)
print(df.Personalized)
Отпечатки
0 the name Alex belonging to IDTag is a common name
1 Judging the Alex of IDTag, I feel its a girl's...
Используйте понимание списка:
df["Comment"] = [c.replace("NameTag", n).replace("IDTag", i)
for c, n, i in zip(df['Comment'], df['Name'], df['ID'])]
print (df)
ID Name Comment
0 A1 Alex the name Alex belonging to A1 is a common name
1 A2 Alice Judging the Alice of A2 , I feel its a girl's...
Учитывая дублированный dataFrame «тест»:
test = pd.DataFrame({
'ID': ['A1', 'A2'],
'Name': ['Alex', 'Alice'],
'Comment': ["the name NameTag belonging to IDTag is a common name", "Judging the NameTag of IDTag, I feel its a girl's name"]})
test
Выход:
ID Name Comment
0 A1 Alex the name NameTag belonging to IDTag is a commo...
1 A2 Alice Judging the NameTag of IDTag, I feel its a gir...
Этот цикл for делает то, что вам нужно, я думаю,
for row in range(test.shape[0]):
name = test['Name'].loc[row]
id = test['ID'].loc[row]
test['Comment'].loc[row] = test['Comment'].loc[row].replace('NameTag', name)
test['Comment'].loc[row] = test['Comment'].loc[row].replace('IDTag', id)
test
Выход:
ID Name Comment
0 A1 Alex the name Alex belonging to A1 is a common name
1 A2 Alice Judging the Alice of A2, I feel its a girl's name
Для общего метода, который работает с любым количеством столбцов, вы можете использовать регулярное выражение и понимание списка:
import re
cols = ['ID', 'Name']
pattern = '|'.join([f'{x}Tag' for x in cols]) # 'IDTag|NameTag'
r = re.compile(fr"\b({pattern})\b")
df['Comment'] = [r.sub(lambda m: d.get(m.group(1)), s)
for d, s in zip(df[cols].add_suffix('Tag').to_dict('index').values(),
df['Comment'])]
Выход:
ID Name Comment
0 A1 Alex the name Alex belonging to A1 is a common name
1 A2 Alice Judging the Alice of A2, I feel its a girl's name
Пытаться :
import pandas as pd
df = pd.DataFrame({
'ID':['A1','A2'],
'Name':['Alex','Alice'],
'Comment':["the name NameTag belonging to IDTag is a common name","Judging the NameTag of IDTag, I feel its a girl's name"]
})
for i in range(len(df['Comment'])):
df.loc[i,'Comment'] = df.loc[i,'Comment'].replace('IDTag',df.loc[i,'ID']).replace('NameTag',df.loc[i,'Name'])
Выходной фрейм данных