[英]AttributeError: 'NoneType' object has no attribute 'get' - How to solve it when I even have the data and no field is None?
[英]Get values from a dict in an column. AttributeError: 'NoneType' object has no attribute 'get' when a value is "None"
我有这个df
simbolo puntas ultimoPrecio
10 AE38 {'cantidadCompra': 79668.0, 'precioCompra': 60... 6080.00
11 AL41C None 36.50
我从“puntas”列中的字典中获得第一个值。
p['Cant_Compra']=[x.get('cantidadCompra',0) for x in p['puntas']]
output:
simbolo Cant_Compra ultimoPrecio
10 AE38 79668.0 6080.00
但如果值为None ,则第 11 行会出现下一条错误消息:
AttributeError: 'NoneType' object 没有属性 'get'
我能做什么?
import ast
from io import StringIO
# sample data
s = """simbolo|puntas|ultimoPrecio
AE38|{'cantidadCompra': 79668.0, 'precioCompra': 60}|6080.00
AL41C|None|36.50"""
df = pd.read_csv(StringIO(s), sep='|')
df['puntas'] = df['puntas'].apply(ast.literal_eval)
# convert the dict column to a dataframe and assign the values to your column
df['Cant_Compra'] = pd.DataFrame(df['puntas'].to_dict()).T['cantidadCompra']
simbolo puntas ultimoPrecio \
0 AE38 {'cantidadCompra': 79668.0, 'precioCompra': 60} 6080.0
1 AL41C None 36.5
Cant_Compra
0 79668
1 None
这有效:
def fun(x):
if x==None:
return None
return x['cantidadCompra']
p['Cant_Compra']=p['puntas'].apply(func=fun)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.