[英]TypeError: Object of type int64 is not JSON serializable | pandas aggregation functions and json.dumps() error
Pandas aggregation functions return TypeError: Object of type int64 is not JSON serializable. Pandas 聚合函数返回类型错误:Object 类型 int64 不是 JSON 可序列化。
Here is the dataframe:这是 dataframe:
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df
Out[47]:
col1 col2
0 1 3
1 2 4
Here is how I am aggregating the column:这是我聚合该列的方式:
sum_col = df.col1.sum()
sum_col
Out[49]: 3
But as soon as I do json.dumps() it gives a type error:但是一旦我执行 json.dumps() 它就会出现类型错误:
data = json.dumps(sum_col)
data
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-50-5d4b966e64cc> in <module>
----> 1 data = json.dumps(sum_col)
2 data
TypeError: Object of type int64 is not JSON serializable
I resolved this one.我解决了这个。
Pandas aggregation functions (like sum, count and mean) returns a NumPy int64 type number, not a Python integer. Although it looks exactly like a python integer. Pandas 聚合函数(如 sum、count 和 mean)返回 NumPy int64 类型的数字,而不是 Python integer。虽然它看起来完全像 python integer。
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
sum_col = df.col1.sum()
type(sum_col)
Out[52]: numpy.int64
This can be fixed by using python's int() function.这可以通过使用 python 的 int() function 来修复。
sum_col = int(df.col1.sum())
data = json.dumps(sum_col)
data
Out[56]: '3'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.