Имеется файл stepssample.xml <recipes> <recipe> <id>44123</id> <steps> <step…
- User
Имеется файл steps_sample.xml 44123 in 1 / 4 cup butter , saute carrots , onion , celery and broccoli stems for 5 minutes add thyme , oregano and basil saute 5 minutes more add wine and deglaze pan add hot chicken stock and reduce by one-third add worcestershire sauce , tabasco , smoked chicken , beans and broccoli florets simmer 5 minutes add cream , simmer 5 minutes more and season to taste drop in remaining butter , piece by piece , stirring until melted and serve immediately smoked chicken: on a covered grill , slightly smoke boneless chicken , cooking to medium rare chef meskan uses applewood chips and does not allow the grill to become too hot 67664 mix all the ingredients using a blender pour into popsicle molds freeze and enjoy ! 38798 combine all ingredients in a large bowl and mix well shape into one-inch balls cover and refrigerate or freeze until ready to bake preheat oven to 350 degrees place on ungreased baking sheet and bake until light brown 35173 lay out sandwich rolls on jelly roll pans / cookie sheets melt butter , mix in italian dressing mix using a pastry or bbq brush , graciously apply seasoned butter to the top of the"bottom bun" and the top of the top bun don’t miss this step , i don’t know why , but it does make a difference ! here is where i create an assembly line w / the bottoms of the buns layer each bun w / ham , then swiss cheese , turkey , then cheddar cheese , pepperoni , then mozzerella cheese place"lids" on buns and place in 425 degree oven for approximly 12-15 minutes , or until you see the tops start to turn golden brown
Есть файл recipes_sample 2.csv с полями name, id, minutes, contributor_id, submitted, n_steps, description
Загрузите данные из файла recipes_sample.csv в таблицу recipes. Для строк, которые содержат пропуски в столбце n_steps, заполните этот столбец на основе файла steps_sample.xml. Строки, в которых столбец n_steps заполнен, оставьте без изменений.
Не используй для этого базу данных. Используй только библиотеки python такие как xml.etree.ElementTree, pandas, numpy
- Assistant
Решение:
Импортируем необходимые библиотеки:
import xml.etree.ElementTree as ET import pandas as pd import numpy as np
Загрузим данные из файла с помощью pandas и преобразуем столбцы в соответствующие типы:
df = pd.read_csv('recipes_sample.csv') df['id'] = df['id'].astype(np.int64) df['minutes'] = df['minutes'].astype(np.int64) df['contributor_id'] = df['contributor_id'].astype(np.int64) df['submitted'] = pd.to_datetime(df['submitted'])
Создадим функцию для получения количества шагов в рецепте из файла xml:
def get_n_steps(recipe_id): tree = ET.parse('steps_sample.xml') root = tree.getroot() steps = root.findall(".//recipe[id='{}']/steps/step".format(recipe_id)) return len(steps)
Теперь используем функцию, чтобы заполнить пропущенные значения в столбце n_steps:
for index, row in df.iterrows(): if pd.isnull(row['n_steps']): n_steps = get_n_steps(row['id']) df.at[index, 'n_steps'] = n_steps
Сохраняем полученную таблицу в файл:
df.to_csv('recipes_updated.csv', index=False)