Skip to main content
 首页 » 编程设计

python之Dataframe 使用分组的行值作为行名

2025年05月04日26think

我刚开始使用 python (pandas),现在我有了第一个问题。 我有一个包含以下行名称的数据框:

ID  A    Class 
1  True  [0,5] 
2  False [0,5] 
3  True  [5,10] 
4  False [10,20] 
5  True  [0,5] 
6  False [10,20] 

现在我正在寻找一个很酷的解决方案,在那里我可以做这样的事情:

Class  True   False 
[0,5]   2      1 
[5,10]  1      0 
[10,20] 0      2 

我想计算一个 Class 有多少 True 和 False 有快速解决方案吗?我的 Dataframe 可能有超过 200 万个条目。

请您参考如下方法:

您可以使用 pivot_table做聚合。之后,只需格式化列名和索引以匹配您想要的输出即可。

# Perform the pivot and aggregation. 
df = pd.pivot_table(df, index='Class', columns='A', aggfunc='count', fill_value=0) 
 
# Format column names and index to match desired output. 
df.columns = [c[1] for c in df.columns] 
df.reset_index(inplace=True) 

结果输出:

     Class  False  True 
0    [0,5]      1     2 
1  [10,20]      2     0 
2   [5,10]      0     1 

编辑:

上述解决方案假定 'Class' 列的元素是字符串。如果它们是列表,您可以执行以下操作:

df['Class'] = df['Class'].map(tuple) 
**original solution code here** 
df['Class'] = df['Class'].map(list)