请检查以下代码,我想将dtype int64转换为其原生python类型int。
dfCredit = pd.DataFrame(credits_List)
dfCredit['date'] = pd.to_datetime(dfCredit['date'], format='%d-%m-%Y')
sum_Credit_Bal = dfCredit.groupby(pd.Grouper(key='date', freq='1M')).sum()
avg_Credit_Bal = dfCredit.groupby(pd.Grouper(key='date', freq='1M')).mean()
avg_Credit_Bal['No. of transactions'] = sum_Credit_Bal['No. of transactions'].astype(int)
print("--------------")
print("\nAverage amount Credited per month :\n\n ", avg_Credit_Bal)
print("--------------")
print(avg_Credit_Bal.dtypes)
js = [{"Average amount Credited per month": avg_Credit_Bal.to_dict()}]
s3object = s3.Object("bank-statement-demo","BankOutput.json")
s3object.put(Body=(bytes(json.dumps(js).encode('UTF-8'))))
我试图在Amazon Lambda服务中运行代码,但出现以下错误
“ TypeError:类型为'int64'的对象不可JSON序列化”。那就是为什么我需要将其转换为它的本机python类型
输出
Average amount Credited per month :
Credit No. of transactions
Month
Jun-18 4644.500000 4
Jul-18 11142.000000 2
Aug-18 12148.750000 4
Sep-18 2830.477143 7
Oct-18 4664.250000 4
Nov-18 8381.500000 2
--------------
Credit float64
No. of transactions int64
dtype: object
期望的答案
No. of transactions int
答案 0 :(得分:1)
因此,看来Amazon s3对dtypes有点敏感,因此为了使其兼容,您可以先转换为int
,然后再转换为object
,以便兼容:
avg_Credit_Bal['No. of transactions'] = sum_Credit_Bal['No. of transactions'].astype(int).astype(object)
如果您查看元素的类型,它将输出object
,表明它是一个通用的python对象:
type(avg_Credit_Bal['No. of transactions'][0])
将输出object
答案 1 :(得分:0)
要将numpy dtypes转换为本地Python dtypes,您有两个选择:
选项1:
sum_Credit_Bal['No. of transactions'].item()
选项2:
np.asscalar(sum_Credit_Bal['No. of transactions'])