Using Python I am trying to access a field which is in string format in a CSV file which has a list of dictionaries.
one row of train['list_of_production_companies']
"[{'name': 'Lions Gate Films', 'id': 35}, {'name': 'Vertigo Entertainment', 'id': 829}, {'name': 'Gotham Group', 'id': 3672}, {'name': 'Tailor Made', 'id': 24557}, {'name': 'Mango Farms', 'id': 24558}, {'name': 'Quick Six Entertainment', 'id': 24561}]"
train['list_of_production_companies'] = train['production_companies'].apply(lambda x: [i['name'] for i in x] if i[name] != {} else [])
NameError Traceback (most recent call last) in () ----> 1 train['list_of_production_companies'] = train['production_companies'].apply(lambda x: [i.name for i in x] if i.name != {} else [])
C:\\ProgramData\\Anaconda3\\lib\\site-packages\\pandas\\core\\series.py in apply(self, func, convert_dtype, args, **kwds) 3190
else: 3191 values = self.astype(object).values -> 3192 mapped = lib.map_infer(values, f, convert=convert_dtype) 3193 3194 if len(mapped) and isinstance(mapped[0], Series):pandas/_libs/src\\inference.pyx in pandas._libs.lib.map_infer()
in (x) ----> 1 train['list_of_production_companies'] = train['production_companies'].apply(lambda x: [i.name for i in x] if i.name != {} else [])
NameError: name 'i' is not defined
Your comprehension is incorrect in the lambda function.
Use:
train['list_of_production_companies'] = train['production_companies'].apply(lambda x: [i['name'] if 'name' in i else [] for i in x])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.