python - Pandas - 对所有列进行分组并在原始数据框中进行标记

标签 python pandas

我有一个DataFrame带列'Id'这是独一无二的,并且 'A', 'B', 'C'等等...

有不同的行,其中所有值 'A', 'B', 'C'是相同的。我想给他们一个组名(从 1 开始的运行索引)。

例如:

df = pd.DataFrame({"A": [1, 1, 1, 2], "B": [3, 4, 4, 4], "C": [5, 5, 5, 5]})
df
Out[127]: 
   A  B  C
0  1  3  5
1  1  4  5
2  1  4  5
3  2  4  5

将成为

   A  B  C  grp
0  1  3  5    1
1  1  4  5    2
2  1  4  5    2
3  2  4  5    3

我知道我可以分组['A', 'B', 'C']并获取 key ,但是,我必须以未优化的方式迭代 key 和数据帧。我未能以优化的方式做到这一点

最佳答案

使用GroupBy.ngroup :

df['grp'] = df.groupby(['A', 'B', 'C']).ngroup() + 1
print (df)

   A  B  C  grp
0  1  3  5    1
1  1  4  5    2
2  1  4  5    2
3  2  4  5    3

如果列已排序:

df['grp'] = pd.factorize([tuple(x) for x in df.values])[0] + 1

关于python - Pandas - 对所有列进行分组并在原始数据框中进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52034526/

相关文章:

python - Pydub for python 2.7 [Windows 7]

python - 如何扩展输出显示以查看 Pandas DataFrame 的更多列?

python - 在 Pandas 中,如果列最初为空,如何使用 fillna 将整个列填充为字符串?

python - 提取 Excel 工作表的样式并将其应用于 Pandas DataFrame

python - 如何在 Python 3 中获取组合 Unicode 字符的显示宽度?

python - 在 Python 中将 snake_case 转换为 lowerCamelCase

Python Pandas : Select columns that their content does not contain a value

python - 如何在 matplotlib 中的单个矩形网格中绘制多个图?

python - &符号在打印功能中如何工作?

python - 如何在 Ubuntu 上删除多个版本的 python