python - 根据 python 中的 cut 对 pandas 数据帧进行排序?

标签 python sorting pandas

如果我使用 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/

相关文章:

Python 3.3.2 - 如何在 Windows 上运行脚本

python - 如何在 Django ModelForm 中过滤 ManyToManyField 选项?

python-3.x - 在 Pandas 数据框中组合具有重叠时间段的行

python - dataframe.describe() 抑制科学记数法

python - 如何对 pandas 数据框中的字母数字列进行排序

python - Pandas groupby 计数在同一行中具有标题

python - 检索 Python 中的命令行参数

python - Pandas LOC 选择值背后的逻辑

algorithm - 合并 k 个列表的最佳方式是什么?

javascript - 返回 value1 - value2 如何导致排序?