如果我使用 pandas.cut
生成像 [0.3, 0.5), ...
这样的 bins 标签,我如何根据这些 bins 升序对数据框进行排序命令?例如。 [-0.4, -0.2)
应该在 [-0.2, 0.0)
之前,等等。示例:
df = pandas.DataFrame({"a": np.random.randn(10)})
# bin according to cut
df["bins"] = pandas.cut(df.a, np.linspace(-2,2,6))
现在如何根据 cut
生成的标签(df["bins"]
列)对 df 进行排序?
最佳答案
如果您先按“a”列对 df 进行排序,则无需对“bins”列进行排序
import pandas as pd
import numpy as np
df = pd.DataFrame({"a": np.random.randn(10)})
# for versions older than 0.17.0
df.sort(by=['a'],inplace=True)
# if running a newer version 0.17.0 or newer then you need
df.sort_values(by=['a'],inplace=True)
# bin according to cut
df["bins"] = pd.cut(df.a, np.linspace(-2,2,6))
df
Out[37]:
a bins
6 -1.273335 (-2, -1.2]
7 -0.604780 (-1.2, -0.4]
1 -0.467994 (-1.2, -0.4]
8 0.028114 (-0.4, 0.4]
9 0.032250 (-0.4, 0.4]
3 0.138368 (-0.4, 0.4]
0 0.541577 (0.4, 1.2]
5 0.838290 (0.4, 1.2]
2 1.171387 (0.4, 1.2]
4 1.770752 (1.2, 2]
关于python - 根据 python 中的 cut 对 pandas 数据帧进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19248234/