python - Obscure KeyError when using groupBy even when key is present
问题描述
I read a CSV from a file, create a trucksAvl
df, then merge it with an existing truckMstr
df and finally do a groupby
on the resulting column.
path=os.getcwd()+'/inputfiles/'+session.get('truckAvlFile')
trucksAvl=pd.read_csv(path)
#truck avl list has no detailsm, get from truck mstr
trucksAvl=trucksAvl.merge(truckMstr.drop_duplicates('Type',keep='last'),on='Type',how='left')
#both has same name, rename old
trucksAvl.rename(columns={'Destination_x':'Destination'},inplace=True)
groupTA=trucksAvl.groupby(('Destination','Type','truckWt','truckVol','Density')).agg({'Count':sum})
groupTA['Used']=0
This worked perfectly finely on my Mac with Python 3.6.9
But when I moved the code to Ubuntu it kept crashing with a key error
解决方案
I tried the following:
- Print column names
- Give an exit path if any of the necessary column names where missing.
- Add an encoding option to the file I was reading
path=os.getcwd()+'/inputfiles/'+session.get('truckAvlFile')
trucksAvl=pd.read_csv(path,encoding='utf-8-sig')
#truck avl list has no detailsm, get from truck mstr
trucksAvl=trucksAvl.merge(truckMstr.drop_duplicates('Type',keep='last')[['Type', 'truckWt', 'truckVol','Density','Destination']], on='Type',how='left')
#both has same name, rename old
trucksAvl.rename(columns={'Destination_x':'Destination'},inplace=True)
print(truckMstr.columns, 'from Debug to ', trucksAvl.columns)
if ('truckWt' in trucksAvl.columns):
if ('truckVol' in trucksAvl.columns):
Final fix was changing group by parentheses from (( ..... )) to ([....])!
Why does Mac allow this and not Ubuntu? I have no idea
groupTA=trucksAvl.groupby(('Destination','Type','truckWt','truckVol','Density')).agg({'Count':sum})
groupTA['Used']=0
groupTA.reset_index(level=groupTA.index.names,inplace=True)
推荐阅读
- blueprism - 将 SAP 表拉入 BluePrism
- sql - SQL GROUP BY 不会为两个表的组合返回正确的结果
- facebook - FBSDK 共享对话框不起作用 React-native ios 模拟器
- token - 微服务授权
- actionscript-3 - 对齐 VGroup 中的子菜单
- vhdl - 双向端口有哪些缺点(Verilog/VHDL)
- c++ - C++:未计算上下文中的 lambda 表达式
- reactjs - 使用 React 图标时未找到模块错误
- javascript - 两个单独的滚动区域简单的解决方案
- android - Crashlytics 和默认异常处理程序