2017-04-19 3 views
0

2つの永続的な列を持つデータを読むために使用しているexcelとcsvという2種類のファイルがあります。Question、Answer、WordとReplacementの2つの一時的な列。データの可用性に基づいてExcelまたはCSVファイルからデータを読み取るにはどうすればよいですか?

私はcsvファイルからデータを読み込み、ファイルの拡張子に基づいて呼び出されるファイルをエクセルためにさまざまな機能を行っています。

は、彼らが存在する場合とそうでないときに基づいて、一時的な列(Wordや交換)からデータを読み込むための方法ですが。 Excelデータを読み出す機能)

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:CSVファイルについて

1):以下の関数定義を参照してください

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 
+0

'pandas.read_csv'と' pandas.read_excel'を考えましたか?それらは、どの列が存在するかに基づいて自動的に読み込まれます。 – tmrlvi

+0

@tmrlvi、私はcsv関数の読み込みにpandas.read_csvを使用しましたが、列ヘッダーはcolnamesで提供する必要があります。しかし、もし私が言葉と交換cloumnsを持っていない場合はどうですか? –

+0

あなたはそれらを提供する必要はありません。あなたがそうでなければ、 'pandas'は名前を推論します。それとも、データにヘッダーが含まれていないのですか? – tmrlvi

答えて

0

私はあなたが達成しようとしたものを全くわからないんだけどしかし、データを読み取って変換することは、次のように行われます:

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") 

これはそれがなかった場合は、あなたのデータはWordReplacement、および["Question", "Word", "Replacemen", "Answer", "asciiIgnoreQues"]が含まれていなかった場合には、あなたの列["Question","Answer", "asciiIgnoreQues"]DataFrameを返します。あなたはすべてのシリーズで機能の要素ごとに実行することができ、私はapplyを使用しました

注意。

関連する問題