如何在列和索引中都有间隔索引的大熊猫中向数据帧添加行?
我试图在一个交叉表中以定义为的大熊猫定义总数:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(500,2))
bins = np.linspace(0, 1, 11)
df['bins_0'] = pd.cut(df[0], bins=bins)
df['bins_1'] = pd.cut(df[1], bins=bins)
# Define crosstable
ct = pd.crosstab(df['bins_0'], df['bins_1'])
# define sumrow
sumrow = ct.sum(axis=0)
我的问题是:如何在这样的表中包含一行?
到目前为止我尝试过的是:
使用“ .loc”添加行不起作用。
ct.loc['total'] = sumrow
结果是 TypeError: cannot append a non-category item to a CategoricalIndex
在这种情况下,尝试重置索引也不起作用,因为使用'ct.reset_index()'会导致 TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
最后,我还将添加一列,每行的总和,但是我想这将需要与添加行相同的过程。
第一个想法是使用margins
在crosstab
:
ct = pd.crosstab(df['bins_0'], df['bins_1'], margins=True, margins_name='Total')
您的解决方案-如果需要新列Total
类别加列axis=1
到sum
:
ct = pd.crosstab(df['bins_0'], df['bins_1'])
ct.columns = ct.columns.add_categories('Total')
ct['Total'] = ct.sum(axis=1)
或DataFrame.loc
如果需要添加新Total
行:
ct = pd.crosstab(df['bins_0'], df['bins_1'])
ct.index= ct.index.add_categories('Total')
ct.loc['Total'] = ct.sum(axis=0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句