Shi*_*pak 5 python json int64 dataframe pandas
Pandas 聚合函数返回 TypeError: int64 类型的对象不可 JSON 序列化。
这是数据框:
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df
Out[47]:
col1 col2
0 1 3
1 2 4
Run Code Online (Sandbox Code Playgroud)
以下是我聚合专栏的方式:
sum_col = df.col1.sum()
sum_col
Out[49]: 3
Run Code Online (Sandbox Code Playgroud)
但是当我执行 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
Run Code Online (Sandbox Code Playgroud)
我解决了这个问题。
Pandas 聚合函数(如 sum、count 和mean)返回 NumPy int64 类型数字,而不是 Python 整数。虽然它看起来和 python 整数一模一样。
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
sum_col = df.col1.sum()
type(sum_col)
Out[52]: numpy.int64
Run Code Online (Sandbox Code Playgroud)
这可以通过使用 python 的 int() 函数来解决。
sum_col = int(df.col1.sum())
data = json.dumps(sum_col)
data
Out[56]: '3'
Run Code Online (Sandbox Code Playgroud)