Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 值\计算结果-将其拆分为其他列?_Python_Pandas_Pandas Groupby - Fatal编程技术网

Python 值\计算结果-将其拆分为其他列?

Python 值\计算结果-将其拆分为其他列?,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,value_counts不允许我用额外的列进一步细分它。基本上,我想做的是在熊猫身上重现这样的东西: 数据在这里 为了简单起见,目前我只想将数据分成3列: 名字,猫(数名),狗(数名) 我一直在四处寻找,尝试过groupby和pivot_表,但我认为我还不够了解 我所尝试的: `animal_names.groupby(['animals_name', 'species']).size().sort_values(ascending=False)` `animal_names.pivot_

value_counts不允许我用额外的列进一步细分它。基本上,我想做的是在熊猫身上重现这样的东西:

数据在这里

为了简单起见,目前我只想将数据分成3列: 名字,猫(数名),狗(数名)

我一直在四处寻找,尝试过groupby和pivot_表,但我认为我还不够了解

我所尝试的:

`animal_names.groupby(['animals_name', 
'species']).size().sort_values(ascending=False)`
`animal_names.pivot_table(
    index=['animals_name', 'species'],
    values='primary_breed',
    aggfunc='count')
`
返回:

`animals_name                    species
Lucy                            Dog        335
Charlie                         Dog        306
Bella                           Dog        248
Luna                            Dog        242
Daisy                           Dog        217
                                          ... 
Mossi                           Dog          1
Mosses                          Dog          1
Mossberg                        Dog          1
Moska                           Dog          1
"Luci" Lucia Rosalin Wicksugal  Dog          1
Length: 16749, dtype: int64`
我试过:

`animal_names.groupby(['animals_name', 
'species']).size().sort_values(ascending=False)`
`animal_names.pivot_table(
    index=['animals_name', 'species'],
    values='primary_breed',
    aggfunc='count')
`
这也不会返回想要的结果

有没有办法做像这样简单的事情
dataframe['animals\u name'].value\u counts()
然后将结果除以另一列(在本例中为物种)?

您就接近了


df=动物名称。数据透视表(index='animals\u name',columns='species',aggfunc='count')
值是可选的,为了帮助您记住pivot是如何工作的,请查看最终的表

  • 第一列的元素是什么?这是你的索引,这里是动物的名字
  • 列名称是什么?每种
  • 通过上述参数可以简单地推断出值,这就是为什么它是可选的
请尝试以下操作:

df = pd.pivot_table(data1,index="Animal's Name",columns = "Species",aggfunc = np.count_nonzero)
这里的data1包含两列,动物名称和物种

输出将显示各物种的名称和计数

将有NAN值,您可以将其替换为零