![](/img/trans.png)
[英]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.