python - 在 Pandas 中创建一个带有标签的列来对 DataFrame 进行分区。

标签 python pandas indexing partitioning cut

我一直在努力寻找一种简洁的方法来执行以下操作。

我有一个看起来像这样的 Pandas DataFrame:

data = {'Ids': [1, 2, 3, 1, 2, 3, 1, 2, 3],  'Value': [32, 56, 87, 12, 45, 78, 
14, 21, 56]}
df=pd.DataFrame(data)

Out[2]: 
    Ids  Value
0    1     32
1    2     56
2    3     87
3    1     12
4    2     45
5    3     78
6    1     14
7    2     21
8    3     56

我想添加另一列,用标签标识每个数据子集(ID 从 1 到 3)。像这样:

Out[3]: 
   Case  Ids  Value
0    A    1     32
1    A    2     56
2    A    3     87
3    B    1     12
4    B    2     45
5    B    3     78
6    C    1     14
7    C    2     21
8    C    3     56

我正在尝试以这种方式使用 pandas.cut() 函数,但我现在取得了很大的成功:

df["test"]=pd.cut(df1.Value, bins=3, labels=["A", "B", "C"], right=False)

是否有使用 Pandas 函数实现我想要的功能的简洁方法?谢谢!

最佳答案

我认为需要cumcount使用 numpy 索引:

a = np.array(["A", "B", "C"])
df['new'] = a[df.groupby('Ids').cumcount()]
print (df)
   Ids  Value new
0    1     32   A
1    2     56   A
2    3     87   A
3    1     12   B
4    2     45   B
5    3     78   B
6    1     14   C
7    2     21   C
8    3     56   C

关于python - 在 Pandas 中创建一个带有标签的列来对 DataFrame 进行分区。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410331/

相关文章:

python - 已安装的 Python 模块 - Python 找不到它们

python - Pandas DataFrame 按两列分组并添加移动平均列

performance - Pandas 中的合并为何如此之快?即使我没有对索引进行排序?

python - 引用 pandas 列的属性与字典表示法

security - Solr 架构更改不会丢失数据且无需使用动态字段

python - 搜索元组列表以查找匹配子字符串的算法方法?

python - 为什么 ZMQ 不会丢弃消息?

python - pip install MySql-python==1.2.4 在 Ubuntu 12.04 上失败

arrays - 无法在Elasticsearch数组中建立索引

MySQL - "many"关系的 "one to many"侧的聚集索引