Python 如何根据数据可用性从excel或csv文件中读取数据?
我有两种文件,excel和csv,我用它们读取数据,其中有两个永久列:问题、答案和两个临时列,它们可能存在也可能不存在Word和Replacement 我做了不同的函数从csv和excel文件中读取数据,这些文件将根据文件扩展名调用 是否有一种方法可以根据临时列(Word和Replacement)的存在时间和不存在时间从临时列中读取数据。请参见下面的函数定义: 1) 对于CSV文件:Python 如何根据数据可用性从excel或csv文件中读取数据?,python,excel,csv,pandas,Python,Excel,Csv,Pandas,我有两种文件,excel和csv,我用它们读取数据,其中有两个永久列:问题、答案和两个临时列,它们可能存在也可能不存在Word和Replacement 我做了不同的函数从csv和excel文件中读取数据,这些文件将根据文件扩展名调用 是否有一种方法可以根据临时列(Word和Replacement)的存在时间和不存在时间从临时列中读取数据。请参见下面的函数定义: 1) 对于CSV文件: def read_csv_file(path): quesData = [] ansData =
def read_csv_file(path):
quesData = []
ansData = []
asciiIgnoreQues = []
qWithoutPunctuation = []
colnames = ['Question','Answer']
data = pandas.read_csv(path, names = colnames)
quesData = data.Question.tolist()
ansData = data.Answer.tolist()
qWithoutPunctuation = quesData
qWithoutPunctuation = [''.join(c for c in s if c not in string.punctuation) for s in qWithoutPunctuation]
for x in qWithoutPunctuation:
asciiIgnoreQues.append(x.encode('ascii','ignore'))
return asciiIgnoreQues, ansData, quesData
2) 用于读取excel数据的函数:
def read_excel_file(path):
book = open_workbook(path)
sheet = book.sheet_by_index(0)
quesData = []
ansData = []
asciiIgnoreQues = []
qWithoutPunctuation = []
for row in range(1, sheet.nrows):
quesData.append(sheet.cell(row,0).value)
ansData.append(sheet.cell(row,1).value)
qWithoutPunctuation = quesData
qWithoutPunctuation = [''.join(c for c in s if c not in string.punctuation) for s in qWithoutPunctuation]
for x in qWithoutPunctuation:
asciiIgnoreQues.append(x.encode('ascii','ignore'))
return asciiIgnoreQues, ansData, quesData
我不完全确定您试图实现什么,但读取和转换数据,即
pandas
方式,如下所示:
def read_file(path, typ):
if typ == "excel":
df = pd.read_excel(path, sheetname=0) # Default is zero
else: # Assuming "csv". You can make it explicit
df = pd.read_csv(path)
qWithoutPunctuation = df["Question"].apply(lambda s: ''.join(c for c in s if c not in string.punctuation))
df["asciiIgnoreQues"] = qWithoutPunctuation.apply(lambda x: x.encode('ascii','ignore'))
return df
# Call it like this:
read_data("file1.csv","csv")
read_data("file2.xls","excel")
read_data("file2.xlsx","excel")
如果您的数据不包括Word
和Replacement
,则会返回一个DataFrame
,其中列为[“问题”、“答案”、“asciiIgnoreQues”]
,如果数据不包括[“问题”、“单词”、“替换人”、“答案”、“asciiIgnoreQues”]
注意,我使用了<代码>应用程序>代码>,使您可以在所有系列上运行一个函数。
您考虑过“代码>熊猫”。它们将根据存在的列自动读取。@tmrlvi,我在读取csv函数中使用了pandas.read_csv,但列标题必须以colnames提供。但是如果我没有单词和替换克隆呢?你不必提供它们。如果你没有,pandas
推断出它们的名字。或者您的数据不包含标题?我的数据包含标题(问题、答案、单词、替换)。所以你是说如果我没有在代码中提供colname,pandas将从第二行读取?无论如何,它从第二行读取,除非你提供header=None