错误的熊猫数据帧read_json python3.5.9 上的排序



超过10 行的数据帧在转换为 json 并返回 pandas 后在 python3.5.9 上错误排序。数据帧。

from pandas import DataFrame, read_json
columns = ['a', 'b', 'c']
data = [[1*i, 2*i, 3*i] for i in range(11)]
df = DataFrame(columns=columns, data=data)
print(df)
#      a   b   c
# 0    0   0   0
# 1    1   2   3
# 2    2   4   6
# 3    3   6   9
# 4    4   8  12
# 5    5  10  15
# 6    6  12  18
# 7    7  14  21
# 8    8  16  24
# 9    9  18  27
# 10  10  20  30
new_df = read_json(df.to_json())
print(new_df)
#      a   b   c
# 0    0   0   0
# 1    1   2   3
# 10  10  20  30   # this should be the last line
# 2    2   4   6
# 3    3   6   9
# 4    4   8  12
# 5    5  10  15
# 6    6  12  18
# 7    7  14  21
# 8    8  16  24
# 9    9  18  27

因此,使用read_json创建的数据帧似乎正在对字符串 (1,10,2,3,...( 而不是整数 (1,2,3..( 等索引进行排序。

使用 Python 3.5.9 生成的行为(默认,2020 年 1 月 4 日 04:09:01((docker 镜像 python:3.5-stretch(

在我的本地机器上一切似乎都运行良好(Python 3.8.1(默认,2019 年 12 月 21 日,20:57:38((。

pandas==0.25.3 在两个实例上都使用。

有什么方法可以在不升级 python 的情况下解决此问题?

使用sort_values对列a上的数据帧进行排序。如下所示:

new_df = read_json(df.to_json())
#sort column
print(new_df.sort_values('a'))
#sort index
print(new_df.sort_index())
#ouput
a   b   c
0    0   0   0
1    1   2   3
2    2   4   6
3    3   6   9
4    4   8  12
5    5  10  15
6    6  12  18
7    7  14  21
8    8  16  24
9    9  18  27
10  10  20  30
``

最新更新