在Python中替换 CSV 文件的列值
让我们看看如何在Python中替换 CSV 文件的列值。 CSV 文件只不过是一个逗号分隔的文件。
方法一:使用Native Python方式
使用replace()方法,我们可以轻松地将一个文本替换为另一个文本。在下面的代码中,让我们有一个输入 CSV 文件作为“csvfile.csv”并以“读取”模式打开。 join() 方法将 CSV 文件的所有行放入一个可迭代对象中,并将它们连接成一个字符串。然后,我们可以对整个字符串使用 replace() 方法,并且可以执行单个/多个替换。在整个字符串中,搜索给定的文本并将其替换为指定的文本。
例子:
输入文件将是:
Python3
# reading the CSV file
text = open("csvfile.csv", "r")
#join() method combines all contents of
# csvfile.csv and formed as a string
text = ''.join([i for i in text])
# search and replace the contents
text = text.replace("EmployeeName", "EmpName")
text = text.replace("EmployeeNumber", "EmpNumber")
text = text.replace("EmployeeDepartment", "EmpDepartment")
text = text.replace("lined", "linked")
# output.csv is the output file opened in write mode
x = open("output.csv","w")
# all the replaced text is written in the output.csv file
x.writelines(text)
x.close()
Python3
# importing the module
import pandas as pd
# making data frame from the csv file
dataframe = pd.read_csv("csvfile1.csv")
# using the replace() method
dataframe.replace(to_replace ="Fashion",
value = "Fashion industry",
inplace = True)
dataframe.replace(to_replace ="Food",
value = "Food Industry",
inplace = True)
dataframe.replace(to_replace ="IT",
value = "IT Industry",
inplace = True)
# writing the dataframe to another csv file
dataframe.to_csv('outputfile.csv',
index = False)
输出:
方法二:使用 Pandas DataFrame
我们可以将 CSV 文件作为 DataFrame 读取,然后应用replace()方法。
Python3
# importing the module
import pandas as pd
# making data frame from the csv file
dataframe = pd.read_csv("csvfile1.csv")
# using the replace() method
dataframe.replace(to_replace ="Fashion",
value = "Fashion industry",
inplace = True)
dataframe.replace(to_replace ="Food",
value = "Food Industry",
inplace = True)
dataframe.replace(to_replace ="IT",
value = "IT Industry",
inplace = True)
# writing the dataframe to another csv file
dataframe.to_csv('outputfile.csv',
index = False)
输出: