get_dummies 和一起计数

2023-10-19Python开发问题
1

本文介绍了get_dummies 和一起计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个数据框,其中包含不同的案例"作为行,其中有一个 id 和一个类别:

I have a dataframe with different "cases" as rows, in which there's an id and a category:

df = DataFrame({ 'id':[1122,3344,5566,5566,3344,5566,1122,3344], 
            'category':['health','transport','energy','energy','transport','transport','transport','energy']})

    category    id
0   health      1122
1   transport   3344
2   energy      5566
3   energy      5566
4   transport   3344
5   transport   5566
6   transport   1122
7   energy      3344

我正在尝试找到一种既可以获取类别的虚拟变量并对其进行计数的好方法,所以通过上面的示例我会得到:

I'm trying to find a good way to both get dummies of the categories and also count them, so with the above example I would get this:

     health  transport  energy
1122    1        1          0
3344    0        2          1
5566    0        1          2

有什么想法吗?

推荐答案

你可以使用pivot_table() 方法:

In [71]: df.pivot_table(index='id', columns='category', aggfunc='size', fill_value=0)
Out[71]:
category  energy  health  transport
id
1122           0       1          1
3344           1       0          2
5566           2       0          1

或:

In [76]: df.pivot_table(index='id', columns='category', aggfunc='size', fill_value=0).rename_axis(None, 1)
Out[76]:
      energy  health  transport
id
1122       0       1          1
3344       1       0          2
5566       2       0          1

这篇关于get_dummies 和一起计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10