pandas 用panda Dataframe 中另一列的值替换列中的单词

gab6jxml  于 2023-02-11  发布在  其他
关注(0)|答案(5)|浏览(174)

在下表中,我想创建一个新列或更新“注解”列,以便将占位符单词“NameTag”替换为列“名称”中的值,并将单词“IDTag”替换为列“ID”中的值
| 识别号|姓名|评论|
| - ------|- ------|- ------|
| A1|亚历克斯|属于IDTag的名称NameTag是通用名称|
| A2|爱丽丝|看身份证上的姓名标签,我觉得是个女孩的名字|
我想要这样的输出...
| 识别号|姓名|评论|
| - ------|- ------|- ------|
| A1|亚历克斯|属于A1的名称Alex是常用名称|
| A2|爱丽丝|看A2的爱丽丝,我觉得是个女孩的名字|
我尝试Pandas替换功能,但它不工作,以列名替换单词...获取以下错误
ValueError:Series.replace不能使用dict-value和非None to_replace

5ktev3wc

5ktev3wc1#

给定复制的dataFrame "test":

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
yptwkmov

yptwkmov2#

对于一个可以处理任意列数的泛型方法,可以使用正则表达式和列表解析:

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
kkbh8khc

kkbh8khc3#

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...
ux6nzvsh

ux6nzvsh4#

使用列表理解:

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...
p8ekf7hl

p8ekf7hl5#

使用.apply和lambda:

df["Comment"] = df.apply(lambda x: x["Comment"].replace("NameTag", x["Name"]), axis=1)

相关问题