我正在创建一个票证跟踪项目,其中有一个保存票证信息的数据框。然后我将此数据帧存储到csv文件中。数据帧将在程序开始时初始化
列值之一是列表。当您使用以下代码行将pandas数据帧存储在csv文件中:self.ticketDF.to_csv(self.ticketCSVFilePath)
时,它用双引号将列表括起来。当您读回它时,它现在被解释为一个字符串,而不是一个列表。在我的示例中,您可以在comments列下看到带有双引号的列表
这是我的文件-tickets.csv:
Ticket ID,Subject,Project,Description,Priority,Comments
PROT-18,testSubject,testProject,testDescription,testPriority,"['comment1', 'comment2', 'comment3']"
PROT-19,testSubject,testProject,testDescription,testPriority,"['comment4', 'comment5', 'comment6']"
我正在使用以下两个函数初始化pandas数据帧:
def initializeTicketDF(self):
if path.exists(self.ticketCSVFilePath) and path.getsize(self.ticketCSVFilePath) > 0:
self.ticketDF = pd.read_csv(self.ticketCSVFilePath) #reading the csv file into the dataframe
self.ticketDF.set_index('Ticket ID', inplace=True) #I am setting the index to the Ticket ID
self.columnToList("Comments") #Calling my function that currently does the
#workaround
def columnToList(self, columnName):
count = 0 #this represents the current row in the dataframe
for x in self.ticketDF['Comments']: #x holds the "Comments" value for every row
x = x.replace('[', '') #replace left and right brackets
x = x.replace(']', '')
x = re.findall('\'([^\']*)\'', x) #get a list of all values between single quotes
self.ticketDF[columnName][count] = x #store the list back into the dataframe
count += 1
如上图所示,为了解决这个问题,我将分别替换每个括号,然后使用以下行获取单个引号之间的所有值的列表:x = re.findall('\'([^\']*)\'', x)
然后将该列表逐行存储回dataframe
我也尝试过使用csv.DictReader/Writer,它也做了同样的事情
有没有一种方法可以在不修改字符串的情况下读取csv中的列表?有没有正则表达式可以用来清理列表的字符串
任何想法都将不胜感激。谢谢
您可以将转换后的列传递给^{} :
^{} 将安全地计算类似于列表的简单表达式
相关问题 更多 >
编程相关推荐