Python如何用引用表替换列中所有匹配的文本,引用表需要替换列中多个匹配的文本

2024-09-28 05:25:13 发布

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

嗨,我是一个全新的Python,但我希望有人能告诉我的绳索。你知道吗

我有一个csv引用表,其中包含1000多行,具有唯一的Find值,引用表示例:

|Find          |Replace     |
------------------------------
|D2-D32-dog    |Brown       |
|CJ-E4-cat     |Yellow      |
|MG3-K454-bird |Red         |

我需要在另一个csv文件中查找和替换文本。另一个文件中需要查找和替换的列的示例(超过2000行):

|Pets                                  |
----------------------------------------
|D2-D32-dog                            |
|CJ-E4-cat, D2-D32-dog                 |
|MG3-K454-bird, D2-D32-dog, CJ-E4-cat  |
|T2- M45 Pig                           |
|CJ-E4-cat, D2-D32-dog                 |

我需要的是python查找并替换,返回以下内容,如果没有引用,则返回原始值:

|Expected output    |
---------------------
|Brown              |
|Yellow, Brown      |
|Red, Brown, Yellow |
|T2- M45 Pig        |
|Yellow, Brown      |

先谢谢你。你知道吗

仅供参考-我没有任何编程经验,通常使用Excel,但被告知Python将能够实现这一点。所以我尝试了一下,希望能达到上面的效果-但是它返回了无效的语法错误。。。你知道吗

import pandas as pd

dfRef1 = pd.read_csv(r'C:\Users\Downloads\Lookup.csv')
#File of Find and Replace Table

df= pd.read_csv(r'C:\Users\Downloads\Data.csv')
#File that contains text I want to replace

dfCol = df['Pets'].tolist()
#converting Pets column to list from Data.csv file 

for x in dfCol:
    Split = str(x).split(',')
#asking python to look at each element within row to find and replace

newlist=[]
for index,refRow in dfRef1.iteritems():
     newRow = []
     for i in Split:
              if i == refRow['Find']:
              newRow.append(refRow['Replace']
              else
              newRow.append(refRow['Find'])
              newlist.append(newRow)
    newlist

#if match found replace, else return original text
#When run, the code is Returning - SyntaxError: invalid syntax
#I've also noticed that the dfRef1 dtype: object

我走对了吗?任何建议都将不胜感激。 我理解excelvlookup的概念,但是,因为单元格值包含多个查找项,我需要在同一单元格中替换这些项,所以我无法在Excel中这样做。你知道吗

再次感谢。你知道吗


Tags: csvtofindreplacecatd2cjdog
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:13

您可以将excel文件保存为CSV,以使您的生活更轻松 然后剥离文件,使其仅包含表,而不包含任何不必要的信息。你知道吗

使用熊猫将CSV文件加载到python:

import pandas as pd
df_table1 = pd.read_csv("file/path/filename.csv")
df_table2 = pd.read_csv("file/path/other_filename.csv")

df_table1[['wanted_to_be_replaced_col_name']] = df_table2[['wanted_col_to_copy']]

有关更多信息和更复杂的任务,请访问熊猫文档@https://pandas.pydata.org/

提示:对于大量的列,请检查iloc函数

相关问题 更多 >

    热门问题