2016-04-25 19 views
0

私は現在、自分で作成したcsvファイルの列と列の両方を構成するcsvファイル( 'tableau_input.csv')を作成しています。私は次のコードを試しました:Pythonを使用して.csvファイルを別の.csvファイルに追加します

def make_tableau_file(mp, current_season = 2016): 
    # Produces a csv file containing predicted and actual game results for the current season 
    # Tableau uses the contents of the file to produce visualization 

    game_data_filename = 'game_data' + str(current_season) + '.csv' 
    datetime_filename = 'datetime' + str(current_season) + '.csv' 

    with open('tableau_input.csv', 'wb') as writefile: 
     tableau_write = csv.writer(writefile) 
     tableau_write.writerow(['Visitor_Team', 'V_Team_PTS', 'Home_Team', 'H_Team_PTS', 'True_Result', 'Predicted_Results', 'Confidence', 'Date']) 

     with open(game_data_filename, 'rb') as readfile: 
      scores = csv.reader(readfile) 
      scores.next() 

      for score in scores: 
       tableau_content = score[1::] 
       # Append True_Result 
       if int(tableau_content[3]) > int(tableau_content[1]): 
        tableau_content.append(1) 
       else: 
        tableau_content.append(0) 
       # Append 'Predicted_Result' and 'Confidence' 
       prediction_results = mp.make_predictions(tableau_content[0], tableau_content[2]) 
       tableau_content += list(prediction_results) 

       tableau_write.writerow(tableau_content) 

     with open(datetime_filename, 'rb') as readfile2: 
      days = csv.reader(readfile2) 
      days.next() 

      for day in days: 
       tableau_write.writerow(day) 

'tableau_input.csv'は私が作成しているファイルです。 'Visitor_Team'、 'V_Team_PTS'、 'Home_Team'、 'H_Team_PTS'の列は 'game_data_filename'(tableau_content = score [1 ::]など)からのものです。 'True_Result'、 'Predicted_Results'、 'C​​onfidence'の列は、最初のforループで作成された列です。 これまでの作業はすべて機能しますが、最後に、上記と同じ構造を使用して 'datetime_filename'の 'Date'列データに追加しようとしましたが、 'tableau_input'ファイルを開くと、 'Date' 。誰かがこの問題を解決できますか?以下の情報については

は、 'game_data_filename' と 'datetime_filename' のそれぞれのcsvファイルのスクリーンショット(NB:datetime値は、日時書式である)ある enter image description here

enter image description here

+0

デバッガを使って何を試しましたか?ファイルは 'readfile2'の内容で開きますか?また、これはおそらく、すべての入力行を最初に書き、次にすべての日付行を書き出します。両方のファイルを開き、両方を一緒に追加してから書き込みたいのですか? –

+0

はい私はreadfile2(datetime値)にコンテンツを持っていますし、基本的には新しいCSVファイル 'tableau_input'に両方のファイルの内容を追加するという考え方です。私はそれを認識しませんでした。これを達成する方法がありますか? – DiamondDogs95

+0

ファイルの末尾に日付行がありますか? –

答えて

0

それは、私のようにこれをテストするのは難しいです入力がどのように表示されるべきか分かりませんが、次のように試してみてください。

def make_tableau_file(mp, current_season=2016): 
    # Produces a csv file containing predicted and actual game results for the current season 
    # Tableau uses the contents of the file to produce visualization 

    game_data_filename = 'game_data' + str(current_season) + '.csv' 
    datetime_filename = 'datetime' + str(current_season) + '.csv' 

    with open('tableau_input.csv', 'wb') as writefile: 
     tableau_write = csv.writer(writefile) 
     tableau_write.writerow(
      ['Visitor_Team', 'V_Team_PTS', 'Home_Team', 'H_Team_PTS', 'True_Result', 'Predicted_Results', 'Confidence', 'Date']) 

     with open(game_data_filename, 'rb') as readfile, open(datetime_filename, 'rb') as readfile2: 
     scoreReader = csv.reader(readfile) 
     scores = [row for row in scoreReader] 
     scores = scores[1::] 
     daysReader = csv.reader(readfile2) 
     days = [day for day in daysReader] 
     if(len(scores) != len(days)): 
      print("File lengths do not match") 
     else: 
      for i in range(len(days)): 
       tableau_content = scores[i][1::] 
       tableau_date = days[i] 
       # Append True_Result 
       if int(tableau_content[3]) > int(tableau_content[1]): 
        tableau_content.append(1) 
       else: 
        tableau_content.append(0) 
       # Append 'Predicted_Result' and 'Confidence' 
       prediction_results = mp.make_predictions(tableau_content[0], tableau_content[2]) 
       tableau_content += list(prediction_results) 
       tableau_content += tableau_date 

       tableau_write.writerow(tableau_content) 

これは両方のファイル読み込み部分を1つにまとめたものです。

以下のご質問を1として:これは、すべての要素がscoreReaderからの行の1つであることと、scoresと呼ばれるリストを作成するリスト内包を使用しています

scoreReader = csv.reader(readfile) 
scores = [row for row in scoreReader] 
scores = scores[1::] 

scorereadergeneratorなので、行を要求するたびに、それがなくなるまで私たちは1つを吐き出します。

2番目の行scores = scores[1::]は、ヘッダーを必要としないので、リストの最初の要素を切り捨てるだけです。

詳細情報についてはこれらを試してみてください。

Generators on Wiki
List Comprehensions

幸運を!

+0

いいですね。私はこれを試みたが、私に "TypeError:type '_csv.reader'のオブジェクトにlen()がありません。 – DiamondDogs95

+0

"範囲(制限)内の "i"を置き換えようとしました: "for i in scores:" "限界" varを取り除く。しかし、他の 'TypeError:' _csv.reader 'オブジェクトには、この行を指す属性' __getitem__ 'がありません: "tableau_content = scores [i] [1 ::]" – DiamondDogs95

+0

csv.reader()オブジェクトはシーケンスではなく、インデックスで行にアクセスすることはできません。 – DiamondDogs95

関連する問題