可以使用Python中的pandas库来解决这个问题。具体步骤如下:
import pandas as pd
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'foo', 'bar', 'foo'],
'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
'C': [1, 2, 2, 1, 2, 1, 1, 2]})
groups = df.groupby('A')['B']
for name, group in groups:
print(name)
print(group)
输出结果为:
bar
1 one
3 three
6 one
Name: B, dtype: object
foo
0 one
2 two
4 two
5 one
7 three
Name: B, dtype: object
说明:以上示例代码中,我们先创建了一个DataFrame,并在其中指定了三列A、B、C。然后我们以"A"列来进行分组,然后遍历每个分组并输出组名(name)及其对应的元素(group)。
总结:可以使用Pandas的groupby()函数来方便地按列基于出现次数分组。
上一篇:按列计算总和
下一篇:按列聚合Pandas数据框