使用Python将一个.csv列添加到另一个.csv文件中

时间:2016-04-25 10:47:53

标签: python mysql csv

我正在编写一个脚本,我正在创建一个csv文件('tableau_input.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','Confidence'是在第一个for循环中创建的列。 到目前为止,一切正常但最后我尝试使用与上面相同的结构添加'datetime_filename'中的'Date'列数据,但是当我打开'tableau_input'文件时,我的'Date'列中没有数据。有人能解决这个问题吗?

有关信息,以下是“game_data_filename”和“datetime_filename”的csv文件的屏幕截图(nb:datetime值采用日期时间格式) enter image description here

enter image description here

1 个答案:

答案 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)

这将两个文件读取部分合二为一。

根据您的问题:

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

这使用list comprehension创建一个名为scores的列表,其中每个元素都是scoreReader中的一行。由于scorereadergenerator,每当我们要求它排成一行时,它会为我们吐出一个,直到没有更多。

第二行scores = scores[1::]只是删除了列表的第一个元素,因为你不需要标题。

欲了解更多信息,请尝试以下方法:

Generators on Wiki
List Comprehensions

祝你好运!