0

Есть определенный датасет (CSV файл) содержащий инфу о фильмах:

Title,Rating,Votes,Gross,Genre,Metascore,Certificate,Director,Year,Description,Runtime
Sen to Chihiro no kamikakushi,8.6,"747,148",$10.06M," Adventure, Family",96,U,Hayao Miyazaki,2001,"[""\nDuring her family's move to the suburbs, a sullen 10-year-old girl wanders into a world ruled by gods, witches, and spirits, and where humans are changed into beasts.""]",125 min
The Lion King,8.5,"1,041,158",$422.78M," Adventure, Drama",88,U,Roger Allers,1994,"['\nLion prince Simba and his father are targeted by his bitter uncle, who wants to ascend the throne himself.']",88 min

Нужно из первого CSV файла сделать новый, используя из датасета только столбцы Director Rating Votes

Соответственно вопрос: Как записать новую таблицу в файл используя только данные нужных мне столбцов. Дошел только до переписки всех данных в новый CSV (пытался сначала записать столбец директоров):

import csv
directors = list()
fieldnames = None
with open("TopAnimated.csv", mode = "r") as table:
    t = csv.DictReader(table)
    fieldnames = t.fieldnames
    for row in t:
      if row["Director"]:
        directors.append(row)

with open("sorted_table.csv", mode = "w") as sorted_table:
  st = csv.DictWriter(sorted_table, fieldnames)
  st.writeheader()
  st.writerows(directors)

1 ответ 1

1

Возьмите Pandas и не мучайтесь:

import pandas as pd

df = pd.read_csv("TopAnimated.csv")
df = df[['Director', 'Rating', 'Votes']]
df.to_csv("sorted_table.csv")

Там могут быть какие-то тонкости настройки чтения и записи, но в целом должно быть вот так просто.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.