gpt4 book ai didi

python - 捕获异常并返回空数据帧

转载 作者:太空狗 更新时间:2023-10-30 01:06:21 25 4
gpt4 key购买 nike

我查询数据库并将结果保存为数据框,然后我通过 factorizepivot_table 对其进行转换。这在数据库查询返回数据时工作正常,但在没有返回数据时抛出错误(这是预料之中的)。如何捕获此异常并返回空数据框?

#When dataframe is non-empty, transformation works fine:
print df

sale name year
0 41 Jason 2012
1 24 Molly 2012
2 31 Jason 2013
3 32 Jason 2014
4 31 Molly 2014


df['groups'] = (pd.factorize(df.year)[0] + 1).astype(str)

df1 = (df.pivot_table(index='name', columns='groups', values=['sale', 'year']))
df1.columns = [''.join(col) for col in df1.columns]
print (df1)

sale1 sale2 sale3 year1 year2 year3
name
Jason 41.0 31.0 32.0 2012.0 2013.0 2014.0
Molly 24.0 NaN 31.0 2012.0 NaN 2014.0

#But when dataframe is empty, factorize by pivot_table throws error

df = pd.DataFrame(columns=['sales','name','year'])
df1 = (df.pivot_table(index='name', columns='groups', values=['sale', 'year']))
df1.columns = [''.join(col) for col in df1.columns]
print (df1)

DataError:没有要聚合的数字类型

最佳答案

try:
df1 = df.pivot_table(index='name', columns='name', values=['sale', 'year'])
except pd.core.groupby.DataError:
df1 = pd.DataFrame()
except:
raise

感谢 brenbarn,他在 How can I catch a pandas DataError? 找到了 dataerror 的错误名称

关于python - 捕获异常并返回空数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38122456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com