The TypeError implies that data in the context of the code is a list, yet an attempt is made to access it using a string key (e.g., data['slug']). This indicates that the structure of data is different from what you expect. It should indeed be a dictionary if you need to access keys like 'slug', 'value', etc.
First, let's check the structure of the param_dict by printing some example entries. After you confirm the structure, we can proceed with the fix.
Here's a small modification to include debugging to print the param_dict:
# Creating `param_dict` and printing samples for debugging
param_dict = grouped.groupby('param_id').apply(lambda x: x.to_dict('records')).to_dict()
# Print some entries in param_dict to understand its structure
for key, value in param_dict.items():
print(f'param_id: {key}')
print(f'value: {value}')
print('-'*20)
# Initialize an empty list to store results
result_list = []
# Process each row in DF1
for index, row in DF1.iterrows():
formula = row['formula']
primary_formula = row['formula']
category = row['category']
base_infmodel = row['base_infm']
# Find all the parameter ids in the formula using regex
param_ids = re.findall(r'{(\d+)}', formula)
param_ids = list(map(int, param_ids)) # Convert param_ids to integers
# Generate all possible combinations of slugs, values, and labels for the given param_ids
valid_param_ids = [param_id for param_id in param_ids if param_id in param_dict]
possible_combinations = product(*(param_dict[param_id] for param_id in valid_param_ids))
for combination in possible_combinations:
temp_formula = formula
values = []
slugs = []
add_item_labels = []
for param_id, data in zip(param_ids, combination):
print(f'data: {data}') # Print data to understand its structure
slug = data['slug']
value = data['value']
add_item_label = data['addItemLabel']
temp_formula = temp_formula.replace(f'{{{param_id}}}', slug)
values.append(value)
slugs.append(slug)
add_item_labels.append(add_item_label)
form_datas = [{'id': pid, 'value': f"'{val}'"} for pid, val in zip(param_ids, values)]
result_list.append({
'idf': row['idf'],
'primary_formula': primary_formula,
'param_ids': param_ids,
'base_infmodel': base_infmodel,
'category': category,
'formula': temp_formula,
'slug': '; '.join(slugs),
'value': '; '.join(values),
'json_value': form_datas,
'addItemLabel': '; '.join(add_item_labels)
})
If data is indeed a dictionary with the keys as expected, the issue might be due to the way param_dict is being created.
Here's a refined exception handling to ensure proper dictionary access, and addressing potential list issues:
from itertools import product
import pandas as pd
import re
# Sample data
data1 = {
'idf': [22, 44, 55, 443],
'category': [114, 114, 116, 114],
'formula': ['predlozheniya_uslug/{716}/{719}', 'predlozheniya_uslug/{716}/{720}', 'predlozheniya/{716}/{720}', 'predlozheniya/{716}/{716}/{720}']
}
# DF1 = pd.DataFrame(data1)
data2 = {
'param_id': [716, 716, 716, 716, 716, 716, 719, 719, 719, 719, 719, 719, 719, 720],
'slug': ['it_internet_telekom', 'nyani_sidelki', 'krasota_zdorove', 'bytovye_uslugi', 'delovye_uslugi', 'oborudovanie_proizvodstvo',
'buhgalteriya_finansy', 'konsultirovanie', 'nabor_i_korrektsiya_teksta', 'perevod', 'yuridicheskie_uslugi',
'buhgalteriya_finansy', 'konsultirovanie', 'translation_services'],
'addItemLabel': ['IT, маркетинг', 'Няни, сиделки', 'Красота, здоровье', 'Бытовые услуги', 'Деловые услуги', 'Оборудование, производство', 'Бухгалтерия, финансы', 'Консультирование',
'Набор и коррекция текста', 'Перевод', 'Юридические услуги', 'Бухгалтерия, финансы', 'Консультирование',
'Translation services'],
'value': ['MTAxOTU=', 'MTAxOTY=', 'MTAxOTc=', 'MTAyMDA=', 'MTAyMDE=', 'MTAyMDI=', 'MTAyMzU=', 'MTAyMzY=', 'MTAyMzg=', 'MTAyMzk=', 'MTAyNDE=', 'MTAyMzU=', 'MTAyMzY=', 'MTAyMzk=']
}
DF2 = pd.DataFrame(data2)
data3 = {
'category': [114, 114, 114, 114, 114, 114],
'parent_value': ['MTAyMDE=', 'MTAyMDE=', 'MTAyMDE=', 'MTAyMDE=', 'MTAyMDE=', 'MzE1NTIwOA=='],
'value': ['MTAyMzg=', 'MTAyMzk=', 'MTAyMzU=', 'MTAyMzY=', 'MTAyNDE=', 'MTAyNDE=']
}
DF3 = pd.DataFrame(data3)
DF2 = pd.read_csv('parameters_all.csv')
DF3 = pd.read_csv('parameter_child_parent.csv')
# DF1 = pd.read_csv('formula_all.csv')
bad_brand = pd.read_csv('bad_brand.txt')
bad_brand_list = bad_brand['url'].to_list()
odezhda2rang = pd.read_csv('formula_tovar_3rang.csv')
# odezhda2rang_list= odezhda2rang['url'].to_list()
odezhda2rang_list = bad_brand['url'].to_list()
pattern = r'{([^{}]*)}'
# Initialize an empty list to store the extracted values
control_values_list = []
DF1 = DF1[11100:144447]
# DF1 = DF1 .loc[DF1 ['formula'].isin(odezhda2rang_list)]
# Iterate through each row in the DataFrame
for index, row in DF1.iterrows():
formula = row['formula']
# Find all matches of the pattern in the formula
matches = re.findall(pattern, formula)
# Append the matched values to the list
control_values_list.extend(matches)
# Transform the extracted values to integers
control_values_list = [int(value) for value in control_values_list]
# Filter DF2 for relevant param_ids
DF2 = DF2.loc[DF2['param_id'].isin(control_values_list)]
# DF2 = DF2.loc[~DF2['slug'].isin(bad_brand_list)]
columns_to_convert = ['param_label', 'slug', 'addItemLabel', 'value']
DF2[columns_to_convert] = DF2[columns_to_convert].astype(str)
# Group by param_id and aggregate the first 20 values
grouped = DF2.groupby('param_id').nth(8)
# Create a dictionary of param_id groups
param_dict = grouped.groupby('param_id').apply(lambda x: x.to_dict('records')).to_dict()
# Print some entries in param_dict to understand its structure
for key, value in param_dict.items():
print(f'param_id: {key}')
print(f'value: {value}')
print('-'*20)
# Initialize an empty list to store results
result_list = []
# Process each row in DF1
for index, row in DF1.iterrows():
formula = row['formula']
primary_formula = row['formula']
category = row['category']
base_infmodel = row['base_infm']
# Find all the parameter ids in the formula using regex
param_ids = re.findall(r'{(\d+)}', formula)
param_ids = list(map(int, param_ids)) # Convert param_ids to integers
# Generate all possible combinations of slugs, values, and labels for the given param_ids
valid_param_ids = [param_id for param_id in param_ids if param_id in param_dict]
possible_combinations = product(*(param_dict[param_id] for param_id in valid_param_ids))
for combination in possible_combinations:
temp_formula = formula
values = []
slugs = []
add_item_labels = []
for param_id, data in zip(param_ids, combination):
# Handling potential list issues
if isinstance(data, dict):
slug = data['slug']
value = data['value']
add_item_label = data['addItemLabel']
temp_formula = temp_formula.replace(f'{{{param_id}}}', slug)
values.append(value)
slugs.append(slug)
add_item_labels.append(add_item_label)
else:
print(f'Unexpected data format: {data}')
form_datas = [{'id': pid, 'value': f"'{val}'"} for pid, val in zip(param_ids, values)]
result_list.append({
'idf': row['idf'],
'primary_formula': primary_formula,
'param_ids': param_ids,
'base_infmodel': base_infmodel,
'category': category,
'formula': temp_formula,
'slug': '; '.join(slugs),
'value': '; '.join(values),
'json_value': form_datas,
'addItemLabel': '; '.join(add_item_labels)
})
# Convert the result list to a DataFrame
result_df = pd.DataFrame(result_list)
result_df.drop_duplicates(subset=['primary_formula', 'formula'], inplace=True)
# Print the resultant DataFrame
Display the resultant DataFrame
display(result_df)
display(result_df.iloc[0, 2])
This code added debugging prints to understand the structure of param_dict and handled potential issues by checking if data is a dictionary. This should help us further diagnose and correct any issues with the data format.