【问题标题】:Add column from one .csv to another .csv file using Python使用 Python 将列从一个 .csv 添加到另一个 .csv 文件
【发布时间】:2016-04-25 10:47:52
【问题描述】:

我目前正在编写一个脚本,其中我正在创建一个由其他 csv 文件列和我自己创建的列组成的 csv 文件 ('tableau_input.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 文件截图(注意:日期时间值是日期时间格式)

【问题讨论】:

  • 您使用调试器尝试过什么?文件是否以 readfile2 中的内容打开?另外,这大概会先写所有的输入行,然后是下面的所有日期行,你不想打开两个文件,把它们附加在一起然后写吗?
  • 是的,我在 readfile2(日期时间值)中有内容,是的,基本上这个想法是将两个文件的内容附加到我的新 csv 文件“tableau_input”中。我没有意识到这一点。你有办法做到这一点吗?
  • 文件底部有日期行吗?
  • 是的,我的日期行已附加在表格底部,并且“日期”列保持为空

标签: python mysql csv


【解决方案1】:

这很难测试,因为我真的不知道输入应该是什么样子,但试试这样的:

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::]

这使用列表解析来创建一个名为scores 的列表,其中每个元素都是scoreReader 中的行之一。由于scorereadergenerator,所以每次我们向它请求一行时,它都会为我们吐出一个,直到没有更多。

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

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

Generators on Wiki
List Comprehensions

祝你好运!

【讨论】:

  • 听起来不错。我试过了,但它引发了“TypeError:'_csv.reader' 类型的对象没有 len()”
  • 我尝试将“for i in range(limit):”替换为“for i in scores:”并去掉了“limit”var。但它引发了另一个'TypeError:'_csv.reader'对象没有属性'getitem''指向这一行:“tableau_content = score[i][1::]”
  • 它引发了这个错误,因为 csv.reader() 对象不是一个序列,我们不能通过索引访问行。
  • @DiamondDogs95 是的,不知道你的输入数据是什么样的,在这里很难测试。您能否将每个文件中的几行示例数据添加到原始帖子中?
  • 您可以在我的原始帖子中看到 csv 文件的内容。谢谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2023-03-10
  • 2015-11-21
  • 2021-02-26
  • 2021-09-23
相关资源
最近更新 更多